Method of exiting and closing file for both Windows + Linux

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?

Answers


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

Need Your Help

data.table manipulation in R environment

r data.table

I'm handling fairly heavily environments in R lately and I found data.table not to behave reliably when enclosed in environments (passed to functions etc...). I typically get the error:

Creating Angular objects on the parent scope from a directive

javascript angularjs angularjs-directive angularjs-scope

I'm building a simple form in Angular that allows the user to add or remove fields as they please. I've modeled this system off of an array of objects. When you begin the array is empty. When a row...