Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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中,为什么这不起作用。。。。打开(';filename.txt';,';a+;';)写入(';一些示例文件内容\n';)_Python - Fatal编程技术网

在Python中,为什么这不起作用。。。。打开(';filename.txt';,';a+;';)写入(';一些示例文件内容\n';)

在Python中,为什么这不起作用。。。。打开(';filename.txt';,';a+;';)写入(';一些示例文件内容\n';),python,Python,我知道我可以使用下面的代码,并且在编写之后它会很好地关闭文件 with open('filename.txt','a+') as file_: file_.write('Some sample file content\n') 我甚至可以在脚本中的一行保留它,如下所示 with open('filename.txt','a+') as file_: file_.write('Some sample file content\n') 因此,这两种方法似乎都提供或返回了一种TextIOWr

我知道我可以使用下面的代码,并且在编写之后它会很好地关闭文件

with open('filename.txt','a+') as file_:
   file_.write('Some sample file content\n')
我甚至可以在脚本中的一行保留它,如下所示

with open('filename.txt','a+') as file_: file_.write('Some sample file content\n')
因此,这两种方法似乎都提供或返回了一种TextIOWrapper对象类型,允许我写入文件

但是为什么我不能使用下面这一行,或者有没有类似的方法将write函数添加到open指令提供的对象中

with open('filename.txt','a+').write('Some sample file content\n')

如果您使用删除
,则此功能有效:

open('filename.txt','a+').write('Some sample file content\n')
但它不会(必然*)关闭该文件


大致相当于:

import sys
try:
    exc = None, None, None
    y = X.__enter__()
    Z
except Exception as e:
    exc = sys.exc_info()
finally:
    X.__exit__(*exc)
open
返回的对象定义了一个关闭文件的
\uuuuuuuuuuuuuuuuuuuuuu
方法,因此仅执行
open(…).write()
不会实现这一点



*在这样的单行程序中,CPython碰巧也关闭了文件,因为文件对象被垃圾收集。

您不能只调用contextmanager本身的write方法,您需要可以调用的文件对象,但这里的问题是
with open().write()
表示
with
语句试图调用
write
返回值的
enter
方法,而不是
open
。更准确地说,只有当
open
返回的对象被垃圾收集后,文件才会关闭。但这种情况何时发生还不清楚。这可能是立即发生的,也可能是在短暂的延迟后发生的。(或者,如果解释器存在,它可能永远不会发生,不过在这种情况下,文件无论如何都会关闭。)@chepner是的,我补充了这一点。CPython总是在对象超出作用域时立即进行垃圾收集(循环引用除外,循环引用每隔一段时间就会被清理一次),但这对于其他实现来说是不保证的。@谢谢。因此,您能确认文件锁在write语句结束后立即释放吗。@TonyB如果没有父进程对文件有锁,我认为是的。
import sys
try:
    exc = None, None, None
    y = X.__enter__()
    Z
except Exception as e:
    exc = sys.exc_info()
finally:
    X.__exit__(*exc)