我们需要使用python中的open关闭文件吗? [英] Do we need to close a file using open in python?

查看:74
本文介绍了我们需要使用python中的open关闭文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我在网上阅读的内容,以下似乎是一个示例示例,该示例是从包含python中整数数据的二进制文件中读取数据的示例:

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

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

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

在Matlab中,应该在使用完文件后使用 fclose 关闭文件.NumPy中有与此相对应的内容吗?

解决方案

Python等效项是 in_file.close().虽然关闭所有打开的文件始终是一个好习惯,但是python还是比较宽容的-当函数返回时(或者在脚本完成时,如果您在函数外部打开文件),它将自动关闭所有打开的文件处理程序.

另一方面,如果您喜欢使用python的嵌套缩进范围,则可以考虑这样做(自python 2.7起有效):

 ,其中open('1234.bin','rb')作为文件内文件:x = np.fromfile(infile,dtype ='int32')#在文件打开范围之外要做的其他事情 

编辑: 解决方案

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

这篇关于我们需要使用python中的open关闭文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆