Do we need to close a file using open in python? [duplicate] Do we need to close a file using open in python? [duplicate] numpy numpy

Do we need to close a file using open in python? [duplicate]


The python equivalent is in_file.close(). While it's always good practice to close any files you open, python is a little more forgiving - it will automatically close any open file handlers when your function returns (or when your script finishes, if you open a file outside a function).

On the other hand, if you like using python's nested indentation scopes, then you might consider doing this (valid as of python 2.7):

with open('1234.bin', 'rb') as infile:    x = np.fromfile(infile, dtype='int32')# other stuff to do outside of the file opening scope

EDIT: As @ShadowRanger pointed out CPython will automatically close your file handlers at function-return/end-of-script. Other versions of python will also do this, though not in a predictable way/time


You need to close an opened file:

f=open('file')f.close()