首页 > 解决方案 > 如何删除文本文件中的特定行而不留下空行?

问题描述

我的代码:

with open("file_name.txt", "r") as f:
    lines = f.readlines()

with open("file_name.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != thing_to_be_deleted:
            f.write(line)

问题是这会在文件中留下一个空行。

标签: python

解决方案


当您使用 readlines() 方法时,您将文件转换为列表,其中文件的每一行都是列表中的一个值。因此,您可以使用列表方法来管理该文件内容。具体来说,该remove()方法将对您有所帮助。例子:

with open("file_name.txt", "r") as f:
    lines = f.readlines()
    line_to_delete = f'{thing_to_be_deleted}\n'
    while line_to_delete in lines:
        lines.remove(line_to_delete)

with open("file_name.txt", "w") as f:
    for line in lines:
        f.write(line)

推荐阅读