如何正确覆盖文件?

Pyt*_*bie 6 python python-3.x

我想知道如何在 python 中覆盖文件。当我"w"open语句中使用时,我的输出文件中仍然只得到一行。

article = open("article.txt", "w")
article.write(str(new_line))
article.close()
Run Code Online (Sandbox Code Playgroud)

你能告诉我如何解决我的问题吗?

nls*_*bch 3

如果您实际上想要逐行覆盖文件,则必须做一些额外的工作 - 因为唯一可用的模式是read 、write 和apend ,这两种模式实际上都不会进行逐行覆盖。

看看这是否是您正在寻找的:

# 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])
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您首先需要将文件的内容“保存”在缓冲区 ( lines) 中,然后替换它。

原因在于文件模式的工作方式。