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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With