Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Based on what I read on the web, the following seems to be an example of reading data from a binary file consisting of integer data in python:

in_file = open('12345.bin', 'rb');
x = np.fromfile(in_file, dtype = 'int32');

In Matlab, I think the corresponding command is:

in_file = fopen('12345.bin', 'rb');
x = fread(in_file, 'int32');
fclose(in_file);

In Matlab, a file is supposed to be closed using fclose after finishing using it. Is there anything corresponding to this in NumPy?

like image 246
chanwcom Avatar asked Dec 11 '22 19:12

chanwcom


1 Answers

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

like image 76
inspectorG4dget Avatar answered Jan 26 '23 01:01

inspectorG4dget