我们需要在python中使用open来关闭文件吗?

cha*_*com 3 python matlab numpy file

根据我在网上看到的内容,以下似乎是从python中的整数数据组成的二进制文件中读取数据的示例:

in_file = open('12345.bin', 'rb');
x = np.fromfile(in_file, dtype = 'int32');
Run Code Online (Sandbox Code Playgroud)

在Matlab中,我认为相应的命令是:

in_file = fopen('12345.bin', 'rb');
x = fread(in_file, 'int32');
fclose(in_file);
Run Code Online (Sandbox Code Playgroud)

在Matlab中,文件应该fclose在完成使用后关闭.在NumPy中有没有相应的东西?

ins*_*get 10

python等价物是in_file.close().虽然关闭你打开的任何文件总是很好的做法,但python更宽容一些 - 它会在你的函数返回时自动关闭所有打开的文件处理程序(或者当你的脚本完成时,如果你在函数外打开一个文件).

另一方面,如果你喜欢使用python的嵌套缩进范围,那么你可以考虑这样做(从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
Run Code Online (Sandbox Code Playgroud)

编辑:正如@ShadowRanger所指出的, CPython将在function-return/end-of-script中自动关闭文件处理程序.其他版本的python也会这样做,但不是以可预测的方式/时间