如何删除文本文件中的输入?

2024-09-30 22:16:36 发布

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

我现在正在学python。我想问是否有一种方法可以输入数据,在文本文件中定位数据并将其删除

例如,在我的文本文件中

PSP0101 PMF0101 PHP0101

但我只想删除PMF0101。所以会变成这样

PSP0101 PHP0101

谢谢你


Tags: 数据方法定位文本文件psp0101pmf0101php0101
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:36

我想你可以用:

import re
# read the file contents
the_file = open('some_file.txt', 'r')
data = the_file.read()
the_file.close()

# find, replace, and write to file
to_remove = "PMF0101"
data = re.sub(r"{}\s+".format(re.escape(to_remove)), "", data)
the_file = open('some_file.txt', 'w')
the_file.write(data)
the_file.close()

相关问题 更多 >