通常写一个文件,我会做以下事情:
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")
但显然它要重新创建文件对象并重写它。
为什么第一 block 中的代码不起作用?我怎样才能使第二个 block 工作?
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")
至于使用 filehandle = open('file', 'w')
在文件中未显示输入,这是因为文件输出被缓冲 - 只有更大的 block 被写入一个时间。为确保文件在单元格末尾刷新,您可以使用 filehandle.flush()
作为最后一条语句。