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?

horchler
  • 18,384
  • 4
  • 37
  • 73
chanwcom
  • 4,420
  • 8
  • 37
  • 49
  • 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 – inspectorG4dget Dec 29 '15 at 02:29
  • 3
    http://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important – Padraic Cunningham Dec 29 '15 at 02: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). – ShadowRanger Dec 29 '15 at 02:40

2 Answers2

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

Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
3

You need to close an opened file:

f=open('file')
f.close()
rayryeng
  • 102,964
  • 22
  • 184
  • 193
winterli
  • 68
  • 6