简体   繁体   English

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

[英]How to delete empty line from txt file after replacing it

Lets say I have a txt file that goes like this:假设我有一个这样的 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)

After the user has typed Line 2 as his input on the a variable, txt file goes like this:用户在a变量上输入Line 2作为他的输入后,txt 文件如下所示:

Line 1
whitespace/empty line
Line 3

How can I delete the empty line?如何删除空行?

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

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

Split the input into a list of lines.将输入拆分为行列表。 Remove the lines that match the user's input, then join them back together.删除与用户输入匹配的行,然后将它们重新连接在一起。

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')
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM