如何在Python中删除包含特定字符串的特定行而不创建新文件?

2024-06-16 10:03:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上我有一个特殊的问题,我必须使用python在一个文本文件上应用所有CRUD操作。我确实完成了创建,阅读演讲,我也删除了部分,但有两个不同的文本文件(即源文件和目标文件)。现在,我的问题是在python中,我们是否可以删除由特定字符串组成的一行,而不创建新文件(使用现有的源文件)?

你知道吗员工.txt 粗糙度20.0 60.0 彼得派珀15.5 40.0 曼尼什曼农27.5 38.5 卢克·帕帕25 50

这是我的文本文件。现在我从用户那里询问您要删除哪个员工数据行。然后用户将输入刺耳的Patel。 我想删除整行,其中包含严厉的帕特尔。你知道吗

附言:我对Python还不熟悉,正在尝试文件处理。你知道吗

编辑: 所以同时我想出了另一个解决办法。但主要的问题是它再次写入了文本文件的最后一行。你知道吗

with open('employee.txt') as f,open('employee.txt','w') as f2:
    for x in f:
        if 'Harsh Patel' not in x:
            f2.write(x)

所以这个结果是, 第1行彼得•派珀15.5 40.0 第二行马尼什-曼农27.5 38.5 第三行卢克·帕帕25 50 第四行卢克·帕帕25 50

第四行是第三行的副本。你知道吗


Tags: 文件字符串用户intxt目标as员工
3条回答

使用sed

import subprocess
THE_FILE = 'file.txt'
THE_LINE = 'line to delete'
sub = subprocess.call(['sed','-i', '/'+THE_LINE+'/d', THE_FILE  ])

如果你知道这句话,我想你可以试试这个:

THE_LINE = "......."
file = open("filename.txt", "r")
text = file.read()
file.close()
# to delete, replace the line with nothing:
text = text.replace(THE_LINE, "")
file = open("filename.txt", "w")
file.write(text)
file.close()

希望对你有帮助。你知道吗

如果您的文本文件用'\n'分隔,则您可以使用:

THE_LINE = "Harsh Patel"
file = open("filename.txt", "r")
# read the text as a list of lines:
text = file.readlines()
file.close()
# use filter, to filter elements from a list, use lambda to create a mini function:
new_text = filter(lambda element: THE_LINE not in element, text)
file = open("filename.txt", "w")
# use join to make a string out of a list in the format you choose, the string there is empty because we have the '\n' in the list already:
file.write("".join(new_text))
file.close()

要重新检查您的代码,您可以使用此代码将重写为文件:

a = "Harsh Patel 20.0 60.0\nPeter Piper 15.5 40.0\nManish Mannon 27.5 38.5\nLuke Papa 25 50"
file = open("filename.txt", "w")
file.write(a)
file.close()

相关问题 更多 >