我正在尝试删除包含特定字符串的特定行。
我有一个名为numbers.txt的文件,其内容如下:
彼得
汤姆
tom1
严
我要删除的是文件中的tom,因此我创建了以下函数:
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()产出如下:
彼得
严
如您所见,问题在于函数删除了和tom1,但我不想删除tom1。我只想删除汤姆。这是我想要的输出:
彼得
tom1
严
有什么想法可以改变这个功能使之正确吗?
发布于 2011-05-10 09:18:43
更改行文:
if not "tom" in line:至:
if "tom" != line.strip():发布于 2011-05-10 09:17:31
那是因为
if not "tom" in line检查,tom是否不是当前line的子字符串。但是在tom1中,tom是一个子字符串。因此,它被删除。
您可能需要下列之一:
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`发布于 2011-05-10 09:23:59
只是为了好玩,这里有一条两条线。
lines = filter(lambda x:x[0:-1]!="tom", open("names.txt", "r"))
open("names.txt", "w").write("".join(lines))挑战:有人为此贴上一条单线。
您还可以使用文件输入模块获得可读性最高的结果:
import fileinput
for l in fileinput.input("names.txt", inplace=1):
if l != "tom\n": print l[:-1]https://stackoverflow.com/questions/5947833
复制相似问题