简体   繁体   English

Python:搜索字符串并从文本文件中删除该行

[英]Python: searching a string and deleting the line from a text file

I am trying to delete the line that contains a searched phrase if it matches the one from an existing text file.我试图删除包含搜索短语的行,如果它与现有文本文件中的匹配。 It seems to work inconsistently when matching the phrase with the first line of the text file.将短语与文本文件的第一行匹配时,它似乎不一致。 However, after the first line, I have tried matching the phrase in the second and third line and it doesn't seem to delete those lines.但是,在第一行之后,我尝试匹配第二行和第三行中的短语,但似乎没有删除这些行。

phrase = str(raw_input("Enter a phrase:")) 
f = open("old.txt","r")
lines = f.readlines()
f.close()
f = open("new.txt","w")
for line in lines:
    if phrase != line.strip():
        f.write(line)
f.close()

Are you sure that the text file contains lines that have the exact same casing as your input phrase?您确定文本文件包含与输入短语具有完全相同大小写的行吗? Even one character being a slightly different case will result in it being ignored.即使一个字符的大小写略有不同,也会导致它被忽略。

I would suggest using .lower() on "phrase" and "line":我建议在“短语”和“行”上使用 .lower():

if phrase.lower().strip() != line.lower().strip():
    f.write(line)

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

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