我可以在已存在的文件上使用with语句吗?

时间:2013-08-08 19:45:37

标签: python

我有一个我已经打开的文件,我想自动关闭它。是否有任何现有方法将文件包装在with语句中?

3 个答案:

答案 0 :(得分:10)

在Python 3中测试:

>>> f = open('test.txt', 'w')
>>> with f:
...    f.closed
...    f.write('a')


False
1
>>> f.closed
True

是的,你可以。但是,它不会重新打开已经关闭的文件:

>>> f.closed
True
>>> with f:
...    f.write('a')


Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    with f:
ValueError: I/O operation on closed file.

这可能是因为上下文管理器只是可以与with语句一起使用的对象; as <identifier>语句中的with位为提供给with语句的对象提供别名,以便您可以在with语句本身中创建对象而无需放置另一行的变量声明:

>>> f = open('test.txt', 'w')
>>> with f as ff:
...    ff.closed


False

这使得在同一对象上多次使用with语句变得容易(例如,如果对象设置为其__enter__(重新)启动连接,而{{1}关闭连接,同时允许重新打开),这对数据库事务等非常有用。

答案 1 :(得分:4)

这很好用:

f = open('file')
with f:
    print >> f, "Open"

print f.closed  # True

但是这会失败,因为file.__enter__的行为不像递归互斥体:

f = open('file')

with f:
    print >> f, "Open"
    with f:
        print >> f, "Open"
    print >> f, "This errors, as the file is already closed"

答案 2 :(得分:2)

这样的事情可以解决问题:

from contextlib import contextmanager

@contextmanager
def close_file(f):
    yield
    f.close()

with close_file(my_file):
    blabla()