Reputation: 1923
Suppose I have a dictionary of files that I am iterating through. I am doing some with each file and then writing it to report (Note: not using the csv
mod).
file_list = ['f1', 'f2', 'f3', 'f4']
report = "C:/reports/report_%s"%(timestamp)
r = open(report, "w')
What happens if something happens in f3 that crashes the script before it finishes. I can use try-catch
to handle for an error but I don't want to just close the report. Perhaps I want the script to continue. Perhaps there is a power failure while the script is running. Perhaps there are multiple try-catch
statements and I don't want to close for each error. Essentially, I just want to save the file without closing it on each iteration of the list, so that if a crash occurs, I can still retrieve the data written to the report up until that point. How can I do this? I cannot simply do report.save()
, right? I thought about using flush()
with os.fsync()
as explained in another question, but I am not 100% sure that's applicable to my scenario. Any suggestion on how to achieve my goal here?
try:
....do stuff...
report.write(<stuff_output> + "\n")
try:
....do more stuff....
report.write(<stuff_output> + "\n")
except:
continue
report.close()
except Exception as e:
pass
Upvotes: 1
Views: 1309
Reputation: 1923
It appears I was able resolve this issue by simply using flush()
and os.fsync()
within the correct scope and placing the r.close()
outside of the try. So even if it tries and fails it passes or continues and at the end it closes:
try:
for item in file_list:
try:
r.write("This is item: " + item + "\n")
except:
r.flush()
os.fsync(r)
continue
except Exception as e:
pass
r.close()
This would always print "This is item: f1", "This is item: f2", "This is item: f3"
to the report.
Upvotes: 1