Python 'with open' print text file - python

I am trying to add a print to text file for my results as well as the cmd line list that displays. And tried using with open('output.txt', 'w') as f:. Though the code already uses with open(lic) as f:. Can I use multiple "with open" statements? How can I generate a file text printout in addition to the cmd line list?
import time
fips_dict = {}
fips_dict["02000"]="AK"
fips_dict["02013"]="AK, Aleutians East"
fips_dict["02016"]="AK, Aleutians West"
while 1: #repeat forever
count = 0
lic = "//Server/replicated/Userdata/"+raw_input("Account: ")+"/Dmp/LicenseStyle.xml"
print
try: #error handling
with open(lic) as f:
for line in f:
#get and print fips codes and county names
if 'RampEntry' in line:
count += 1
fips_index = line.index('dataValue')+11
code = line[fips_index : fips_index+5]
statecode = line[fips_index : fips_index+2]
if code.isalnum():
print code,fips_dict[code]
elif statecode.isalpha():
print "Entire State of", statecode
print
else:
print "format error in", lic
except IOError: #if file not found
print lic[23:],"not found"
except KeyError: #if no match for FIPS
print "not found"
except:
print "an unexpected error has occured!"
print
now = time.strftime("%c")
print ("%s" % now )
print

Related

How to check if a file is empty? python

I have a code that i am writing to read a txt file and report sum, average, ect... but I also need it to recognize when the txt file is empty or has no numbers in it, and not crash. i have tried os.stat(f).st_size == 0, and os.path.getsize(f) == 0:, and reading the first character too. for some reason my code is not picking up on the exception and keeps continuing on with the rest of the code and then crashes when trying to divide by zero to find the average. I am also not using any external libraries.
#the below code asks for the file name and opens the file :)
while (True):
try:
filename = input("What file would you like to acess?: ")
f = open(filename, "r")
except IOError:
print("File", filename, "could not be opened")
except:
if os.path.getsize(f) == 0:
print("There are no numbers in", filename)
else:
break
#the below line displays the file name :)
print("File Name: ", f.name)
#the below code calculates the sum and prints it :)
sum=0
for n in f:
n=n.strip()
sum=sum+int(n)
print("Sum: ", sum)
#the below code calculates the number of lines and prints it :)
with open(filename, "r") as f:
count = 0
for line in f:
if line != "\n":
count += 1
print("Count: ", count)
#the below code calculates the average and prints it :)
avg = sum/count
print("Average: ", avg)

Game of Life with file read for world generation - string index out of range issue

Like the title says, I've being working on a variant of Conway's Game of Life in python that can read a "world" from a file and generate the starting world from that. However, in my code, I'm being given a "string index out of range" issue at the line while(aLine[currentCharacter] != NEWLINE), and I can't figure out why.
If it helps, in the input files " " is treated as a dead cell, and "*" is treated as a living cell.
Thank you for the help and please let me know if there's any additional info I should provide
def fileReadWorld():
fileOK = False
world = []
row = 0
column = 0
while (fileOK == False):
try:
filename = input("Name of input file: ")
inputfile = open(filename,"r")
fileOK = True
aLine = inputfile.readline()
if(aLine == ""):
print("The file %s" %(filename), "is empty.")
fileOK = False
else:
aLine = inputfile.readline()
row = 0
while(aLine != ""):
currentCharacter = 0
world.append([])
while(aLine[currentCharacter] != "\n"):
world[row].append(aLine[currentCharacter])
currentCharacter = currentCharacter + 1
row = row + 1
aLine = inputfile.readline()
inputfile.close()
maxRows = row
maxColumns = len(world[0])
return(world, maxRows, maxColumns)
except IOError:
print("Problem reading from file %s" %(filename))
fileOK = False
The input file I am using is
*
*
***
(it should display as a 10x10 grid)
Consider this simpler solution with the same result:
def main():
world = []
while True:
try:
filename = input("Name of input file: ")
for aLine in open(filename,"r")
world.append(list(aLine[:-1]))
if world:
maxRows = len(world)
maxColumns = len(world[0])
return world, maxRows, maxColumns
print("The file %s" %(filename), "is empty.")
except IOError:
print("Problem reading from file %s" %filename)
print(main())

Text in file is not printing

I want to print text from a file but the output doesn't show anything.
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
f = open("stock", "a+")
p = f.read()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
if e == '':
stock_screen()
else:
stock_screen()
Anyone know how to fix this?
You can just open the file in read mode, and not append mode. Try this code:
f = open('stock', 'r') -> #(r stands for read mode)
file_contents = f.read()
print (file_contents)
f.close()
To read a file and print, you may want to just open the file in read mode.
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
with open("stock", "r") as f:
p = f.readlines()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
stock_screen() #You just need to call it once
#this entire section can be ignored and instead the above line will do
'''
The if and else does the same thing. So no need to use if statement
if e == '':
stock_screen()
else:
stock_screen()
'''
If you want to read from a file open it in read mode and not append mode. When you open it in append mode the file's position is at the end where it returns nothing.
try this:
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
f = open("stock", "r")
p = f.read()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
if e == '':
stock_screen()
else:
stock_screen()

Python coding for opening and saving data to a file

I am having an issue getting the train function to work correctly in python. I can not modify the def function. I am at the point where I need to get the second file to read lines one at a time for PosList and i need to match the value of movieWordCount[z] in OpenPos. If the file is there, then I am good to incrment column 2 by one of t hat line (segmented by a space). If it is not, then I need the else to append it to the file end. It does not work. It does not append the values if it is missing and I am not sure if it will find the value if it is there. I have been stuck getting thsi to work for two days.
Here is my code segment I am working with:
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
#Now use tokenize to split it apart by space and set to new array for me to call column2
else:
print "not found"
lines.append(movieWordCount[z] + " 1" + "\n")
Here is my full code:
#!/usr/bin/python
#Import Counter
import collections
from collections import Counter
#Was already here but pickle is used for data input and export
import math, os, pickle, re
class Bayes_Classifier:
def __init__(self, trainDirectory = "movie_reviews/"):
#If file listing exists skip to train
if os.path.isfile('iFileList'):
print "file found"
self.train()
#self.classify()
#If file listing does not exist skip to train
if not os.path.isfile('iFileList'):
print "no file"
newfile = 'iFileList'
tempList = set()
subDir = './movie_reviews'
for filenames in os.listdir(subDir):
my_sub_path = os.path.join(os.sep,subDir,filenames)
tempList.add(filenames)
self.save("filenames", "try3")
f = []
for fFileObj in os.walk("movie_reviews/"):
f.extend(fFileObj)
break
pickle.dump(f, open( "save.p", "wb" ))
self.save(f, "try4")
with open(newfile, 'wb') as fi:
pickle.dump(tempList, fi)
#print tempList
self.train()
#self.classify()
def train(self):
'''Trains the Naive Bayes Sentiment Classifier.'''
print "File ready for training"
#Open iFileList to use as input for opening movie files
x = 0
OpenIFileList = open('iFileList','r')
print "iFileList now Open"
#Loop through the file
for line in OpenIFileList:
#print "Ready to read lines"
#print "reading line " + line
if x > 4:
if x % 2 == 0:
#print line
s = line
if '-' in s:
comp = s.split("'")
#print comp[2]
print comp[1] #This is What you need for t he movie file
compValue1 = comp[1]
#Determine Positive/Negative.
#compType is the variable I am storing it to.
compType = compValue1.split("-",2)[1]
#print compType #Prints that middle value like 5 or 1
# This will do the work based on the value.
if compType == '5':
# print "you have a five" #Confirms the loop I am in.
#If file does not exists create it
if not os.path.exists('PosList'):
print "no file"
file('PosList', 'w').close()
#Open file that needs to be reviewed for word count
compValue2 = "movie_reviews/" + compValue1
print compValue2 #Prints the directory and file path
OpenMovieList = open(compValue2,'r')
for commentLine in OpenMovieList:
commentPositive = commentLine.split(" ")
commentPositiveCounter = Counter(commentPositive)
#print commentPositiveCounter # " Comment Pos goes here"
#if commentLine != '' or commentLine != ' ':
#Get first word, second word, ....
if commentLine and (not commentLine.isspace()):
movieWordCount = self.tokenize(commentLine)
y = len(movieWordCount) #determines length of string
print y
z = 0
#print movieWordCount[0] # Shows the zero position in the file.
while z < y:
print "position " + str(z) + " word is " + movieWordCount[z] # Shows the word we are at and position id
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
else:
print "not found"
lines.append(movieWordCount)
z = z + 1
#Close the files
OpenMovieList.close()
OpenPos.close()
x += 1
#for line2 in OpenIFileList.readlines():
#for line in open('myfile','r').readlines():
#do_something(line)
#Save results
#Close the File List
OpenIFileList.close()
def loadFile(self, sFilename):
'''Given a file name, return the contents of the file as a string.'''
f = open(sFilename, "r")
sTxt = f.read()
f.close()
return sTxt
def save(self, dObj, sFilename):
'''Given an object and a file name, write the object to the file using pickle.'''
f = open(sFilename, "w")
p = pickle.Pickler(f)
p.dump(dObj)
f.close()
def load(self, sFilename):
'''Given a file name, load and return the object stored in the file.'''
f = open(sFilename, "r")
u = pickle.Unpickler(f)
dObj = u.load()
f.close()
return dObj
def tokenize(self, sText):
'''Given a string of text sText, returns a list of the individual tokens that
occur in that string (in order).'''
lTokens = []
sToken = ""
for c in sText:
if re.match("[a-zA-Z0-9]", str(c)) != None or c == "\'" or c == "_" or c == '-':
sToken += c
else:
if sToken != "":
lTokens.append(sToken)
sToken = ""
if c.strip() != "":
lTokens.append(str(c.strip()))
if sToken != "":
lTokens.append(sToken)
return lTokens
To open a file for writing, you can use
with open('PosList', 'w') as Open_Pos
As you are using the with form, you do not need to close the file; Python will do that for you at the end of the with-block.
So assuming that the way you add data to the lines variable is correct, you could remove the superfluous code OpenMovieList.close() and OpenPos.close(), and append 2 lines to your code:
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
else:
print "not found"
lines.append(movieWordCount)
with open("PosList", "w") as OpenPos:
OpenPos.write(lines)

No output on command line python

This is my code. when I run it, it simply exits after running. There is nothing printed. Why so ?
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
input.close()
found is a local name in the function checkString(); it stays local because you don't return it.
Return the variable from the function and store the return value:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
return found
for files in listdir():
found = checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
You need to modify to:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
input.close()
return found
found = False
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
found = found or checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
This is because in your original found is only in scope within the function checkString

Categories