Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以对已经存在的文件使用with语句吗?_Python - Fatal编程技术网

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

Python 我可以对已经存在的文件使用with语句吗?,python,Python,我已经打开了一个文件,我想自动关闭它。有没有任何现有的方法可以将文件包装到with语句中?类似这样的方法应该可以做到: from contextlib import contextmanager @contextmanager def close_file(f): yield f.close() with close_file(my_file): blabla() 在Python 3中测试: >>> f = open('test.txt', 'w'

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

类似这样的方法应该可以做到:

from contextlib import contextmanager

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

with close_file(my_file):
    blabla()
在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.
这使得多次使用同一对象上的语句变得很容易,例如,如果对象设置为其uuu enter uuu重新启动连接,而其uuu exit uuu关闭连接,同时允许重新打开连接,这对于数据库事务等可能非常有用。

这很好:

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

print f.closed  # True
但这将失败,因为file.\u enter\u的行为不像递归互斥:

f = open('file')

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

“已经打开”是什么意思?您是否在python shell中打开了它?如果你指的是一个已经存在的文件,是的,你肯定可以使用with语句。我不这么认为,你认为这个机制究竟如何工作?它怎么知道什么时候关门?哇!酷,我还在学新东西。。。这在2.6中起作用also@JoranBeasly,很高兴认识你。我也会在Python 2上测试它,但我没有在这台计算机上安装它,直到现在才忘记了诸如ideone之类的网站。这个答案表明:如果你有一个Python或其他类似交互式友好语言的简单问题,为什么不试试看会发生什么?因为解释器是什么时候对一系列语句中的每个表达式求值的?@Eric那只是tab fail我倾向于在Windows中使用IDLE来处理基本的交互内容,因为它的功能比控制台解释器稍好,而且它不会像控制台版本那样更改解释器提示。编辑以使其更清楚。-1-但这与使用my_文件没有什么不同:向下投票为问题提供了另一种可能的解决方案?向下投票为重新发明python标准库中包含的一个轮子两次,并且-您的文件不为使用close_文件关闭文件my_文件:引发例外Who如果您想了解如何正确执行此操作,请参阅在contextlib中关闭的实现,或PEP中的示例代码。或者,更好的方法是,如果你想要的话,只使用关闭,而不是试图重新实现它。是的,你确实是对的!
f = open('file')

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