I\'m trying to delete a specific line that contains a specific string.
I\'ve a file called numbers.txt with the following content:
You can use regex.
import re
if not re.match("^tom$", line):
output.append(line)
The $ means the end of the string.
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`
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]
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!!)
change the line:
if not "tom" in line:
to:
if "tom" != line.strip():