0

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?

1 Answer 1

6

Note that: f.close doesn't actually close the file, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit
0