我想知道如何在 python 中覆盖文件。当我在 open 语句中使用 "w" 时,我的输出文件中仍然只有一行。
article = open("article.txt", "w")
article.write(str(new_line))
article.close()
你能告诉我如何解决我的问题吗?
请您参考如下方法:
如果您实际上希望逐行覆盖文件,您将不得不做一些额外的工作 - 因为唯一可用的模式是 read , write 和 aappend,它们实际上都不是逐行覆盖。
看看这是否是您要找的:
# Write some data to the file first.
with open('file.txt', 'w') as f:
for s in ['This\n', `is a\n`, `test\n`]:
f.write(s)
# The file now looks like this:
# file.txt
# >This
# >is a
# >test
# Now overwrite
new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
# Get the previous contents
lines = f.readlines()
# Overwrite
for i in range(len(new_lines)):
f.write(new_lines[i])
if len(lines) > len(new_lines):
for i in range(len(new_lines), len(lines)):
f.write(lines[i])
如您所见,您首先需要将文件内容“保存”在缓冲区中(行),然后替换它。
