【发布时间】:2018-09-10 03:29:39
【问题描述】:
作为How do you append to a file?的线程,大多数答案是打开一个文件并附加到它,例如:
def FileSave(content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test1 \n")
FileSave("test2 \n")
我们为什么不直接提取 myfile 并仅在调用 FileSave 时写入。
global myfile
myfile = open(filename)
def FileSave(content):
myfile.write(content)
FileSave("test1 \n")
FileSave("test2 \n")
后一种代码是否更好,因为它只打开文件一次并多次写入?
或者,没有区别,因为 python 内部的内容将保证文件只打开一次,尽管open 方法被多次调用。
【问题讨论】:
-
修改后的代码存在许多与您的问题无关的问题:您以只读模式打开文件,从不关闭文件,您有一个
global什么都不做的声明……
标签: python