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

O.r*_*rka 4 python file with-statement file-writing

通常要写一个文件,我会做以下事情:

the_file = open("somefile.txt","wb")
the_file.write("telperion")
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,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")
Run Code Online (Sandbox Code Playgroud)

但显然它会重新创建文件对象并重写它.

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

Ant*_*ala 7

w标志表示"打开以进行写入并截断文件"; 您可能想要使用a标志打开文件,这意味着"打开要附加的文件".

此外,您似乎正在使用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")
Run Code Online (Sandbox Code Playgroud)

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

  • @O.rka:关于文件中的缓冲:“with”语句创建一个上下文管理器,负责在最后调用“the_file.close()”,从而将文件刷新到磁盘。如果您退出 Jupyter 进程,这些文件应该会出现。 (2认同)