When it is necessary to close a file and when it is not in python?

Python does not close the file for you automatically because it doesn't know when you're done with the file object. You need to either close the file explicitly or wrap your code (which contains the open(...) function) in a with statement. Here is an example form python documentation about pickle module :

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()

And using with which is a much more Pythonic approach, you can do:

with open("filename.pkl", 'r') as f:
    data = cPickle.load(f)

Tags:

Python

File