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?
cPicklethrows exception or not. But since we don't have control over when will that happen it really is a bad practice, i.e. stick withwith.