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

时间:2016-05-13 19:38:54

标签: python file python-3.x

我有一个很大的Python(3)脚本,我试图优化 据我所知,当您使用with open(..., ...) as x时, DON' 需要在"结束时使用.close()。阻止(它自动关闭)。

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

f = open(..., ...)
f.write()
f.close()

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

with open(location, mode) as packageFile:
    packageFile.write()

进入这个:

open(location, mode).write(content).close()

不幸的是,这不起作用,我收到了这个错误:

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'

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

open(location, mode).write(content)

为什么没有open(location, mode).write(content).close()工作,省略.close()功能是否安全?

4 个答案:

答案 0 :(得分:1)

  

我知道你完成操作文件后应该添加.close()

如果您使用with,则不会。

  

为什么open(location, mode).write(content).close()没有工作

因为您没有尝试关闭文件,而是尝试关闭write方法调用的返回值,这是一个整数。你不能关闭一个整数。

  

省略.close()功能是否安全?

没有。如果您在不同的Python实现上运行此代码,或者CPython放弃引用计数,您的写入可能会被任意延迟甚至完全丢失。

如果你真的想把它推到一行,你可以写一个单行with语句:

with open(location, mode) as packageFile: packageFile.write(whatever)

这是不鼓励的,但是比依赖文件对象的终结器为你关闭文件更加沮丧。

答案 1 :(得分:1)

那是因为.(点)运算符从左到右工作。在a.b中,b是传递给a的消息(方法调用)。说

a.b.c...

读取

do b in a and return r1, then
do c in r1 and return r2, then
...

现在open会返回一个响应read消息的对象,但read会返回没有方法str的{​​{1}} / bytes

Bdw,始终在这种情况下使用上下文管理器,即close。我想知道这与优化有什么关系,正如你所说的那样,你在优化脚本时这样做了。

答案 2 :(得分:1)

在我看来,目标是让一个功能一个接一个地发生,但这并不是这里发生的事情。

open(location,mode)返回一个文件: https://docs.python.org/2/library/functions.html#open

的语法中
open(location, mode).write(content)

这实际上相当于

file = open(location, mode)
file.write(content)

open语句成为一个类型文件,它有一个名为write()的函数。 .close()不起作用的原因是file.write()没有名为close()的函数。这是尝试做的是file.function()。function()。

在任何情况下,尝试通过减少行来优化代码都不会明显加快性能,正常的with语句应该同样快。除非你试图去打高尔夫球,这是另一个主题。

祝你有个美好的一天!

答案 3 :(得分: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.

  

为什么没有打开(位置,模式).write(content).close()工作?

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

相关问题