如何评估文件是否关闭? [英] How do I assess if a file is closed?

查看:75
本文介绍了如何评估文件是否关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下内容:

y=open('S:\\02012014EASTERN.TXT','r').readlines()

我不知道该文件现在是否已关闭.我该如何测试?

I don't know whether the file is now closed. How do I test this?

推荐答案

您无法对此进行测试,因为您从未存储过对文件对象的引用.

You can't test for this, because you never stored a reference to the file object.

最好将文件对象用作上下文管理器,以确保关闭文件对象:

It is better to use the file object as a context manager, which ensures that the file object will be closed:

with open('S:\\02012014EASTERN.TXT','r') as ofh:
    y = ofh.readlines()

由于CPython使用引用计数,因此在您的代码中该文件对象将立即关闭并清除,但是您不能指望在其他可能延迟垃圾回收的Python实现中使用此行为.

Because CPython uses reference counting, in your code the file object would be immediately closed and cleared, but you cannot count on this behaviour in other Python implementations where garbage collection may be delayed.

这篇关于如何评估文件是否关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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