Note that: f.close
doesn't do anythingactually 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