At the moment I’m using this code
if __name__=="__main__":
try:
main()
except KeyboardInterrupt:
f.close
print "left!"
Is that the best way to do it? Earlier on in the script a file is being written to and I want to make sure its closed cleanly should the script be terminated. Any views please?
Note that:
f.closedoesn’t actually close the file, you have to call the function:f.close()To answer your question, the best way is using a
withblock. The file will be automatically closed even if an exception is raised: