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)
但显然它会重新创建文件对象并重写它.
为什么第一个块中的代码不起作用?我怎么能让第二块工作?
该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()
用作最后一个语句.
归档时间: |
|
查看次数: |
22556 次 |
最近记录: |