Q:

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

I was trying to write code that manages resources in a responsible way. I understand that a common idiom to make sure a file is closed after using is
with open("filename.txt", 'r') as f:
    # ...use file `f`...

However, I often see people do the following:
data = cPickle.load(open("filename.pkl", 'r'))

I am wondering is that a right way and does Python always close filename.pkl even if cPickle throws an exception? Some explanation (or pointers to articles that explains) whether that is safe?

A:

Python doesn't close the file when you open it.thus when you pass it in following code without wrapping the script by with statement :
data = cPickle.load(open("filename.pkl", 'r'))

You need to close if manually.
This is a 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()

As you can see the file has been closed at the end of code!
Also for more info you read the following python documentation about closing a file :

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>>
>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

