提问者:小点点

替换txt文件后如何删除空行


假设我有一个txt文件,如下所示:

Line 1
Line 2
Line 3
a = input("text to delete from file: ")

with open('save.txt', 'r') as file:
    text = file.read()
with open('save.txt', 'w') as file:
    new_text = text.replace(a, '')
    file.write(new_text)

用户在a变量上输入第2行后,txt文件如下:

Line 1
whitespace/empty line
Line 3

如何删除空行?


共3个答案

匿名用户

将输入拆分为行列表。删除与用户输入匹配的行,然后将它们重新连接在一起。

a = input("text to delete from file: ")

with open('save.txt', 'r') as file:
    text = file.read().splitlines()
new_text = [line for line in text if line != a]

with open('save.txt', 'w') as file:
    file.write('\n'.join(new_text) + '\n')

匿名用户

删除换行符以及用户的文本。

new_text = text.replace(a + '\n', '')

匿名用户

This will save the text with no empy line to the variable final_text.

line_to_delete = "fifth line"

with open("data/test.txt") as file:
    text = file.read()
    print(text)
    text2 = text.replace(line_to_delete, "")

    text3 = [text for text in text2.splitlines() if text]
    final_text = " \n".join(text3) 
    print(final_text)