![](/img/trans.png)
[英]How to delete one line before a specific word in a text file in python
[英]How to delete a line before specific word with python
所以我有文本文件file.txt
例如
something1
something2
something3
line to be removed
2022-07-21 >> Ctrl+S
something4
something5
something6
something7
line to be removed
2022-07-21 >> Ctrl+S
现在如何让它在整个文件中删除Ctrl+S
之前的一行。
这样输出文件将是
something1
something2
something3
2022-07-21 >> Ctrl+S
something4
something5
something6
something7
2022-07-21 >> Ctrl+S
谢谢
这应该可以按需要工作;
keyword = 'Ctrl+S'
new_content = []
with open('textfile.txt', 'r+') as f:
content = f.readlines()
prev_index = 0
for i, line in enumerate(content):
if keyword in line:
new_content += content[prev_index:i - 1]
prev_index = i
new_content += content[prev_index:]
with open('textfile.txt', 'w') as f:
f.write("".join(new_content))
用一个 open 语句试试这个。 希望它可以帮助你。
with open("textfile.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for pos, line in enumerate(lines):
if len(lines)-1 !=pos:
if "Ctrl+S" in lines[pos+1]:
continue
f.write(line)
f.truncate()
你可能会做这样的事情:
with open("python_cisco\programs\list.txt", "r") as f:
lines = f.readlines() # number of bits not to overload your system
for i in range(len(lines)):
try:
if "Ctrl+S" in lines[i]:
lines.remove(lines[i - 1])
except:
pass
with open("python_cisco\programs\list2.txt", "w") as f:
for i in lines:
f.write(i)
这将基本上将列表重写为不同的文件而没有不必要的行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.