4

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?

3
  • 2
    The analog in python is in_file.close(). However, if you forget to do that, python will automatically close the file when the function returns Commented Dec 29, 2015 at 2:29
  • 3
    stackoverflow.com/questions/7395542/… Commented Dec 29, 2015 at 2:36
  • 1
    @inspectorG4dget: CPython will, but it's not a language guarantee in general (PyPy, Jython, and IronPython might get around to closing the file at some point, but not at a predictable time). Commented Dec 29, 2015 at 2:40

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

3

You need to close an opened file:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.