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

标签 python file with-statement file-writing

<分区>

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

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() 作为最后一条语句。

关于python - 使用 "with open() as file"方法,如何多次写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818124/

相关文章:

python - 使用python连接到海康威视摄像头并打开cv

python - python中写入和监听同一个串口

Java - 递归删除父路径的文件和文件夹

c - 在 C 中从文件中读取长行时处理内存

python - 写入文件时的奇怪行为

python - 将字符串作为输入,像计算器一样对其进行计算并返回整数答案的函数

python - 将元组添加到 Python 中的元组列表

c - 使用 C 程序在文件中定位文本

Python "with"语句堆积

r - 在R中,如何使函数内的变量可供该函数内的较低级别函数使用?(with、attach、environment)