Deleting a line from a file in Python

2020-01-31 03:36发布

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?

5条回答
时光不老,我们不散
2楼-- · 2020-01-31 03:53

change the line:

    if not "tom" in line:

to:

    if "tom" != line.strip():
查看更多
Evening l夕情丶
3楼-- · 2020-01-31 03:58

You can use regex.

import re
if not re.match("^tom$", line):
    output.append(line)

The $ means the end of the string.

查看更多
仙女界的扛把子
4楼-- · 2020-01-31 04:06

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`
查看更多
孤傲高冷的网名
5楼-- · 2020-01-31 04:07

I'm new in programing and python (a few months)... this is my solution:

import fileinput

c = 0 # counter
for line in fileinput.input("korrer.csv", inplace=True, mode="rb"):
    # the line I want to delete
    if c == 3: 
        c += 1
        pass
    else:
        line = line.replace("\n", "")
        print line
        c +=1

I'm sure there is a simpler way, just it's an idea. (my English it's not very good looking!!)

查看更多
趁早两清
6楼-- · 2020-01-31 04:18

Just for fun, here's a two-liner to do it.

lines = filter(lambda x:x[0:-1]!="tom", open("names.txt", "r"))
open("names.txt", "w").write("".join(lines))

Challenge: someone post a one-liner for this.

You could also use the fileinput module to get arguably the most readable result:

import fileinput
for l in fileinput.input("names.txt", inplace=1):
    if l != "tom\n": print l[:-1]
查看更多
登录 后发表回答