Python 使用“with open() as file”方法,怎么写不止一次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35818124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using "with open() as file" method, how to write more than once?
提问by O.rka
Usually to write a file, I would do the following:
通常要写一个文件,我会做以下事情:
the_file = open("somefile.txt","wb")
the_file.write("telperion")
but for some reason, iPython (Jupyter) is NOT writing the files. It's pretty weird, but the only way I could get it to work is if I write it this way:
但出于某种原因,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")
But obviously it's going to recreate the file object and rewrite it.
但显然它会重新创建文件对象并重写它。
Why does the code in the first block not work? How could I make the second block work?
为什么第一个块中的代码不起作用?我怎样才能使第二个块工作?
回答by Antti Haapala
The w
flag means "open for writing and truncate the file"; you'd probably want to open the file with the a
flag which means "open the file for appending".
该w
标志的意思是“打开写入并截断文件”;你可能想用a
标志打开文件,这意味着“打开文件进行附加”。
Also, it seems that you're using Python 2. You shouldn't be using the b
flag, except in case when you're writing binary as opposed to plain text content. In Python 3 your code would produce an error.
此外,您似乎使用的是 Python 2。您不应该使用该b
标志,除非您正在编写二进制而不是纯文本内容。在 Python 3 中,您的代码会产生错误。
Thus:
因此:
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")
As for the input not showing in the file using the filehandle = open('file', 'w')
, it is because the file output is buffered - only a bigger chunk is written at a time. To ensure that the file is flushed at the end of a cell, you can use filehandle.flush()
as the last statement.
至于使用 没有在文件中显示的输入filehandle = open('file', 'w')
,这是因为文件输出被缓冲 - 一次只写入更大的块。为确保在单元格末尾刷新文件,您可以将其filehandle.flush()
用作最后一条语句。