【问题标题】:How to delete one line before a specific word in a text file in python如何在python中的文本文件中删除特定单词之前的一行
【发布时间】:2022-07-20 19:49:05
【问题描述】:
所以我有文本文件file.txt 例如
something1
something2
something3
line to be removed
Ctrl+S
something4
something5
something6
something7
line to be removed
Ctrl+S
现在我该如何让它删除整个文件中的 one 行 before 单词 Ctrl+S。
这样输出文件将是
something1
something2
something3
Ctrl+S
something4
something5
something6
something7
Ctrl+S
谢谢
【问题讨论】:
标签:
python
python-3.x
file
【解决方案1】:
也许这会对你有所帮助:
import re
with open('file.txt') as f:
text = f.read()
text = re.sub(r'(Ctrl\+S)(\n[^\n]+)(?=\nCtrl\+S)', '\\1\\3', text)
with open('file.txt', 'w') as f:
f.write(text)
【解决方案2】:
f = open("file.txt",'r')
lines = f.readlines()
f.close()
excludedWord = "whatever you want to get rid of"
newLines = []
for line in lines:
newLines.append(' '.join([word for word in line.split() if word !=
excludedWord]))
f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()
这可能有点用处!