【发布时间】:2016-09-10 03:05:48
【问题描述】:
我正在尝试优化一个相当大的 Python(3) 脚本。
据我了解,当您使用 with open(..., ...) as x 时,不要需要在“with”块的末尾使用 .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() 函数是否安全?
【问题讨论】:
-
您不能通过将多行“推”在一起来“优化”脚本。你最终会做的只是影响可读性,可能会引入这样的错误,并使你的脚本更难维护。 人应该像机器一样阅读程序,它们需要维护,而不是总是由原作者维护。当你试图把东西塞在一起时,它只会让一切变得更加困难。当然,方法链有时很有用,因为它可以防止创建可能代价高昂的临时变量,但从长远来看并不总是值得的。
标签: python file python-3.x