使用"with open() as file"方法,如何写多次?

Using "with open() as file" method, how to write more than once?

通常写一个文件,我会这样做:

the_file = open("somefile.txt","wb")
the_file.write("telperion")

但出于某种原因,iPython (Jupyter) 没有写入文件。这很奇怪,但我唯一能让它工作的方法就是这样写:

with open('somefile.txt', "wb") as the_file:
    the_file.write("durin's day\n")

with open('somefile.txt', "wb") as the_file:
    the_file.write("legolas\n")

但显然它要重新创建文件对象并重写它。

为什么第一块中的代码不起作用?我怎样才能让第二块工作?

w标志表示"open for writing and truncate the file";你可能想用 a 标志打开文件,这意味着 "open the file for appending".

此外,您似乎正在使用 Python 2. 您不应该使用 b 标志,除非您正在编写二进制而不是纯文本内容.在 Python 3 中,您的代码会产生错误。

因此:

with open('somefile.txt', 'a') as the_file:
    the_file.write("durin's day\n")

with open('somefile.txt', 'a') as the_file:
    the_file.write("legolas\n")

至于使用 filehandle = open('file', 'w') 没有在文件中显示的输入,这是因为文件输出被缓冲 - 一次只写入更大的块。为确保文件在单元格末尾刷新,您可以使用 filehandle.flush() 作为最后一条语句。