![](/img/trans.png)
[英]How to delete from specific line until specific line in a file on python
[英]How to delete lines from a file until a specific character? [Python]
我正在尝试编写一个 python 脚本,该脚本遍历文件并对其进行扫描,直到找到给定的单词,然后从该单词中删除文件中的所有行,直到找到下一个给定的单词,如下所示:
Line1
Line2
Line3
Key-Word
Line4
Line5
Key-Word2
Line6
Line7
结果将是:
Line1
Line2
Line3
Key-Word2
Line6
Line7
到目前为止,我已经设法让它检测到关键字,但不确定如何让它删除即将到来的行,然后从 Key-Word2 开始继续
读取文件行,然后将其写回,除了从开始键到停止键的行,这是一个示例:
def erase(file_name: str, start_key: str, stop_key: str):
"""
This function will delete all line from the givin start_key
until the stop_key. (include: start_key) (exclude: stop_key)
"""
try:
# read the file lines
with open(file_name, 'r+') as fr:
lines = fr.readlines()
# write the file lines except the start_key until the stop_key
with open(file_name, 'w+') as fw:
# delete variable to control deletion
delete = False
# iterate over the file lines
for line in lines:
# check if the line is a start_key
# set delete to True (start deleting)
if line.strip('\n') == start_key:
delete = True
# check if the line is a stop_key
# set delete to False (stop deleting)
elif line.strip('\n') == stop_key:
delete = False
# write the line back based on delete value
# if the delete setten to True this will
# not be executed (the line will be skipped)
if not delete:
fw.write(line)
except RuntimeError as ex:
print(f"erase error:\n\t{ex}")
用法:
erase('file.txt', 'Key-Word', 'Key-Word2')
file.txt(输入):
Line1
Line2
Line3
Key-Word
Line4
Line5
Key-Word2
Line6
Line7
运行 function 后:
Line1
Line2
Line3
Key-Word2
Line6
Line7
理想情况下,您应该打开文件两次。 一次读行,一次写。 如果由于某种原因,您在尝试同时读取和写入的 forloop 中遇到错误,您最终可能会得到部分受影响的文件。
您需要小心去除行之间的空白,因为字符“\n”将附加到您的字符串中。
keyword_found = False
with open("line_file.txt", "r") as f:
lines = f.readlines()
with open("line_file.txt", "w") as f:
while (lines):
line = lines.pop(0).strip("\n")
if line == 'you':
keyword_found = True
if line == 'friend':
keyword_found = False
if not keyword_found:
f.write(line + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.