如何正确覆盖文件?

2023-12-19

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

article = open("article.txt", "w")
article.write(str(new_line))
article.close()

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


如果您实际上正在寻找覆盖逐行文件,您将不得不做一些额外的工作 - 因为唯一可用的模式是read ,w仪式和a追加,两者实际上都没有进行逐行覆盖。

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

# 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])

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

这样做的原因这就是文件模式的工作原理。 https://www.tutorialspoint.com/python/python_files_io.htm

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确覆盖文件? 的相关文章

随机推荐