PythonHelp
PythonHelp

Reputation: 27

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

Upvotes: 1

Views: 582

Answers (1)

William Troup
William Troup

Reputation: 13141

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":

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

Upvotes: 1

Related Questions