在Python中关闭文件的显式方法 [英] Explicit way to close file in Python

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

问题描述

请查看以下代码:

for i in xrange(1,5000):
    with open(r'test\test%s.txt' % i, 'w') as qq:
        qq.write('aa'*3000)

它似乎是按照所有Python规则编写的;使用后文件关闭.好像.但是实际上,似乎建议使用(!)系统关闭文件,而不是显式关闭它,因为当我在Resource Monitor上查看时,它会显示很多打开的文件.这给我带来了很多问题,因为在脚本中我使用了大量文件,并且经过很长一段时间后,尽管从源代码中关闭",但仍然出现打开文件过多"错误.

It seems to be written according to all Python rules; files are closing after using. Seems to. But in fact it seems to recommend(!) system to close file, not to close it explicitly because when I'm looking on Resource monitor it shows a lot of open files . It gives me a lot of problems because in my script I use a lot of files and after a long time I got "Too many open files" error despite of 'closing' it from source code.

是否有某种方法可以在Python中显式关闭文件?或者如何检查文件是否真的被关闭了?

Is there some way to explicitly close file in Python? Or how can I check whether the file was really(!) closed or not?

更新:我刚刚尝试使用另一种监视工具-Sysinternals的Handle,它显示了所有正确的信息,我对此表示信任.因此,这可能是资源监视器本身的问题.

Update: I've just tried with another monitoring tool - Handle from Sysinternals and it shows all correct and I trust it. So, it may be problem in Resource monitor itself.

显示打开的文件的屏幕截图:

Screenshot which shows files opened:

推荐答案

您的代码

for i in xrange(1, 5000):
    with open(r'test\test%s.txt' % i, 'w') as qq:
        qq.write('aa' * 3000)

在语义上完全等同于

for i in xrange(1, 5000):
    qq = open(r'test\test%s.txt' % i, 'w')
    try:
        qq.write('aa' * 3000)
    finally:
        qq.close()

与将 with 与文件一起使用是一种确保保留 with 块后立即关闭文件的方法.

as using with with files is a way to ensure that the file is closed immediately after the with block is left.

所以您的问题必须在其他地方.

So your problem must be somewhere else.

也许正在使用的Python环境版本存在一个错误,由于某些原因未调用 fclose().

Maybe the version of the Python environment in use has a bug where fclose() isn't called due to some reason.

但是您可以尝试类似

try:
    qq.write('aa' * 3000)
finally:
    # qq.close()
    os.close(qq.fileno())

直接由系统调用

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

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