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
Solution 1:
change the line:
if not "tom"in line:
to:
if"tom" != line.strip():
Solution 2:
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)identityif"tom\n" != line # checks for complete (un)identity, classical wayif not "tom"==line.strip() # first removes surrounding whitespace from `line`
Solution 3:
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]
Solution 4:
You can use regex.
import re
if not re.match("^tom$", line):
output.append(line)
The $
means the end of the string.
Solution 5:
I'm new in programing and python (a few months)... this is my solution:
import fileinput
c = 0# counterfor line in fileinput.input("korrer.csv", inplace=True, mode="rb"):
# the line I want to deleteif c == 3:
c += 1passelse:
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!!)
Post a Comment for "Deleting A Line From A File In Python"