python关闭文件描述符问题 [英] python close file descriptor question

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

问题描述

我认为这个问题更多的是编码风格,而不是技术问题。

I think this question is more of a "coding style" rather than technical issue.

说我有一行代码:

buf = open('test.txt','r').readlines()
...

文件描述符会自动关闭,还是会保留在内存中?
如果文件描述符没有关闭,什么是更喜欢关闭它的方法?

Will the file descriptor automatically close, or will it stay in the memory? If the file descriptor is not closed, what is the prefer way to close it?

推荐答案

如果将文件对象分配给变量,可以使用 .close )

If you assign the file object to a variable, you can explicitly close it using .close()

f = open('test.txt','r')
buf = f.readlines()
f.close()

首选),您可以使用和关键字(Python 2.5和更高版本) .html> Python文档

Alternatively (and more generally preferred), you can use the with keyword (Python 2.5 and greater) as mentioned in the Python docs:


这是一个很好的做法,使用
关键字在处理文件
对象时。这有一个优点,即

套件完成后
正确关闭文件,即使在路上出现异常
。它也比
短了
try-finally块:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:



>>> with open('test.txt','r') as f:
...     buf = f.readlines()
>>> f.closed
True

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

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