Skip to main content
 首页 » 编程设计

python之如何从文本文件中删除包含特定单词的整行

2025年05月04日28lexus

我制作了一个名为 contacts.txt 的文本文件,其中包含:

pot 2000

derek 45

snow 55

我想获取要删除哪个联系人的用户输入(姓名),然后删除包含该姓名的整行。到目前为止,这就是我所做的:

# ... previous code 
if int(number) == 5: 
    print "\n" 
    newdict = {} 
    with open('contacts.txt','r') as f: 
        for line in f: 
            if line != "\n": 
                splitline = line.split( ) 
                newdict[(splitline[0])] = ",".join(splitline[1:]) 
    print newdict 
    removethis = raw_input("Contact to be removed: ") 
    if removethis in newdict: 
        with open('contacts.txt','r') as f: 
            new = f.read() 
        new = new.replace(removethis, '') 
        with open('contacts.txt','w') as f: 
            f.write(new) 

当我输入“pot”时,我返回到文本文件,只有“pot”被删除,“2000”保留在那里。我试过了

new = new.replace(removethis + '\n', '') 正如其他论坛所建议的那样,但它没有用。

注意事项:

  • 我在其他论坛上阅读的所有内容都要求我创建一个新文件,但我不想这样做;我只想要一个文件。
  • 我已经在第一次打开文件时尝试了“r+”并插入了一个 for 循环,它只选择不包含输入单词的行,但它也不起作用。

请您参考如下方法:

我看到你说这不是重复的,但是这个讨论不等同于你的问题吗?

Deleting a specific line in a file (python)

根据链接中的讨论,我根据您的输入(使用您提供的用户名)创建了一个 .txt 文件并运行了以下代码:

filename = 'smp.txt' 
 
f = open(filename, "r") 
lines = f.readlines() 
f.close() 
 
f = open(filename, "w") 
for line in lines: 
  if line!="\n": 
    f.write(line) 
f.close() 

这样做的目的是删除行之间的空格。 在我看来,这就是您想要的。