关于在Python中关闭文件 [英] about close a file in Python

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

问题描述

我知道,如果在Python中不再使用close,则使用close来关闭文件是一个好习惯.我试图打开大量打开的文件,但没有关闭它们(在同一Python进程中),但是没有看到任何异常或错误.我已经尝试了Mac和Linux.因此,只是想知道Python是否足够聪明,可以管理文件句柄以自动关闭/重用它们,这样我们就不必关心文件关闭了吗?

I know it is a good habit of using close to close a file if not used any more in Python. I have tried to open a large number of open files, and not close them (in the same Python process), but not see any exceptions or errors. I have tried both Mac and Linux. So, just wondering if Python is smart enough to manage file handle to close/reuse them automatically, so that we do not need to care about file close?

先谢谢了, 林

推荐答案

Python 通常,垃圾收集对象将不再使用且不再被引用.这意味着与垃圾回收器的过滤器匹配的打开文件对象完全有可能被清理甚至关闭. 但是;您不应该依赖于此,而应使用:

Python will, in general, garbage collect objects no longer in use and no longer being referenced. This means it's entirely possible that open file objects, that match the garbage collector's filters, will get cleaned up and probably closed. However; you should not rely on this, and instead use:

with open(..):

示例(也是最佳做法):

with open("file.txt", "r") as f:
    # do something with f

注意::如果您关闭文件并在系统上保留打开文件描述符",则最终将开始达到系统的资源限制;特别是"ulimit".您最终将开始看到与打开的文件过多"相关的OS错误. (假定此处为Linux,但其他操作系统也将具有类似的行为.)

NB: If you don't close the file and leave "open file descriptors" around on your system, you will eventually start hitting resource limits on your system; specifically "ulimit". You will eventually start to see OS errors related to "too many open files". (Assuming Linux here, but other OS(es) will have similar behaviour).

重要提示:也是一种良好做法,也可以关闭所有已写入的打开文件,以便正确刷新已写入的数据.这有助于确保数据完整性,避免文件由于应用程序崩溃而意外包含损坏的数据.

Important: It's also a good practice to close any open files you've written too, so that data you have written is properly flushed. This helps to ensure data integrity, and not have files unexpectedly contain corrupted data because of an application crash.

值得注意的是,上面的重要说明是导致写入文件的许多问题的原因.读回去;发现它是空的;但然后关闭您的python程序;在文本编辑器中读取它,并意识到它不为空.

It's worth noting that the above important note is the cause of many issues with where you write to a file; read it back; discover it's empty; but then close your python program; read it in a text editor and realize it's not empty.

演示:一个很好的例子,说明如果不确定确保关闭打开的文件,可能会遇到的资源限制和错误:

Demo: A good example of the kind of resource limits and errors you might hit if you don't ensure you close open file(s):

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> xs = [open("/dev/null", "r") for _ in xrange(100000)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 24] Too many open files: '/dev/null'

这篇关于关于在Python中关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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