打开文件,写入文件而不关闭文件是否安全?

5 python file python-3.x

我有一个很大的Python(3)脚本,我正在尝试优化.
要在使用我的理解with open(..., ...) as x,你不要需要使用.close()在"同向"的结束块(它会自动关闭).

我也知道你完成操作文件后应该添加.close()(如果你没有使用with),如下所示:

f = open(..., ...)
f.write()
f.close()
Run Code Online (Sandbox Code Playgroud)

为了将3行(上图)推入1行,我试图改变这一点:

with open(location, mode) as packageFile:
    packageFile.write()
Run Code Online (Sandbox Code Playgroud)

进入:

open(location, mode).write(content).close()
Run Code Online (Sandbox Code Playgroud)

不幸的是,这没有用,我收到了这个错误:

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    one.save("one.txt", sample)
  File "/home/nwp/Desktop/Python/test/src/one.py", line 303, in save
    open(location, mode).write(content).close()
AttributeError: 'int' object has no attribute 'close'
Run Code Online (Sandbox Code Playgroud)

当我删除.close()这样的行时,同样的行正常工作:

open(location, mode).write(content)
Run Code Online (Sandbox Code Playgroud)

为什么open(location, mode).write(content).close()不起作用,省略.close()功能是否安全?

小智 1

省略 .close() 函数是否安全?

在当前版本的 CPython 中,该文件将在 for 循环结束时关闭,因为 CPython 使用引用计数作为其主要垃圾收集机制,但这是一个实现细节,而不是该语言的功能。

还直接引用user2357112if you ever run this code on a different Python implementation, or if CPython ever abandons reference counting, your write could be arbitrarily delayed or even lost completely.

为什么 open(location, mode).write(content).close() 不起作用?

这是因为我试图.close()在返回时调用该方法open(location, mode).write(content)