Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to delete a specific line that contains a specific string.

I've a file called numbers.txt with the following content:

peter
tom
tom1
yan

What I want to delete is that tom from the file, so I made this function:

def deleteLine():
fn = 'numbers.txt'
f = open(fn)
output = []
for line in f:
    if not "tom" in line:
        output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()

The output is:

peter
yan

As you can see, the problem is that the function delete tom and tom1, but I don't want to delete tom1. I want to delete just tom. This is the output that I want to have:

peter
tom1
yan

Any ideas to change the function to make this correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
725 views
Welcome To Ask or Share your Answers For Others

1 Answer

change the line:

    if not "tom" in line:

to:

    if "tom" != line.strip():

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...