【发布时间】:2016-06-19 11:47:20
【问题描述】:
通常要写一个文件,我会这样做:
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"模式打开文件会删除文件中的所有数据(如果存在)。 -
试试:
the_file = open("somefile.txt", "wb", buffering=False). -
让我们回到你原来的写作。您的写入被缓冲,直到您写入数据块或关闭文件。所以你可能还看不到磁盘上的数据。
标签: python file with-statement file-writing