Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a line from a file in Python

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?

like image 427
Borja Avatar asked May 10 '11 09:05

Borja


2 Answers

change the line:

    if not "tom" in line:

to:

    if "tom" != line.strip():
like image 131
Matic Avatar answered Oct 21 '22 23:10

Matic


That's because

if not "tom" in line

checks, whether tom is not a substring of the current line. But in tom1, tom is a substring. Thus, it is deleted.

You probably could want one of the following:

if not "tom\n"==line # checks for complete (un)identity
if "tom\n" != line # checks for complete (un)identity, classical way
if not "tom"==line.strip() # first removes surrounding whitespace from `line`
like image 28
phimuemue Avatar answered Oct 22 '22 01:10

phimuemue