本文介绍了在Python中从文件中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除包含特定字符串的特定行.

I'm trying to delete a specific line that contains a specific string.

我有一个名为 numbers.txt 的文件,其内容如下:

I've a file called numbers.txt with the following content:

我要删除的是文件中的 tom ,所以我执行了以下功能:

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()

输出为:

如您所见,问题在于该函数删除了 tom tom1 ,但是我不想删除 tom1 .我只想删除 tom .这是我想要的输出:

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:

有什么想法可以更改功能以使其正确执行吗?

Any ideas to change the function to make this correctly?

推荐答案

更改行:

    if not "tom" in line:

收件人:

    if "tom" != line.strip():

这篇关于在Python中从文件中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 13:17