Thanks for all your advice. I decided to try using a with statement (See code below.) since it sounded like the easiest to implement but ended up getting an "OSError: [Errno 2] ENOENT." I tried looking up what this meant but my searches came up with irrelevant information.
Code: Select all
"""
logPunches(fileName)
- a function that opens, reads, appends data to, and rewrites a file given fileName
- returns nothing
"""
def logPunches(fileName):
# Define variables
time = []
time = clock.datetime()
log = []
monthNames = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec')
# See if there is a file to read
with open(fileName, 'r') as readLog:
for line in readLog:
log.append(line)
print("Read line: {0}".format(line))
print("I made it to this point")
# Append new entry to log
log.append('{0}:{1},{2}{3},\n'.format(time[4], time[5], monthNames[time[1]-1], time[2]))
print(log)
# Replace/create file with an updated file using log
writeLog = open(fileName, 'w')
for line in range(len(log)):
writeLog.write(log[line])
writeLog.close()
I then tried using the try statement once again with exception, else, and finally clauses (see code below). Using finally threw a "local variable referenced before assignment" error. I deleted the finally statement which fixed the error but caused the same corrupted data to show up.
Code: Select all
"""
logPunches(fileName)
- a function that opens, reads, appends data to, and rewrites a file given fileName
- returns nothing
"""
def logPunches(fileName):
# Define variables
time = []
time = clock.datetime()
log = []
monthNames = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec')
# See if there is a file to read
try:
readLog = open(fileName, 'r')
except:
print("Error reading file")
else:
for line in readLog:
log.append(line)
print("Read line: {0}".format(line))
finally:
readLog.close()
print("I made it to this point")
# Append new entry to log
log.append('{0}:{1},{2}{3},\n'.format(time[4], time[5], monthNames[time[1]-1], time[2]))
print(log)
# Replace/create file with an updated file using log
writeLog = open(fileName, 'w')
for line in range(len(log)):
writeLog.write(log[line])
writeLog.close()
I think I'm still missing something here. Thoughts?
Thanks for the MSC suggestion. Disabling MSC might not be a bad idea but what I really need is for the pyboard to not open a non-existent file but instead create the file with the new data if the designated file doesn't exist. If the file does exist I want it to read the file add data and re-save the file.