[英]How to remove all lines from text file up until specific string?
我有一個文本文件,里面有很多調試信息,在我需要的數據之前。 我正在使用 python3 嘗試重寫輸出,以便文件以特定的 JSON 標記開頭。 我試圖使用這個解決方案Remove string and all lines before string from file但我得到一個空的輸出文件,所以我認為它沒有找到 JSON 標簽。
這是我的代碼:
tag = '"meta": ['
tag_found = False
with open('file.in',encoding="utf8") as in_file:
with open('file.out','w',encoding="utf8") as out_file:
for line in in_file:
if tag_found:
if line.strip() == tag:
tag_found = True
else:
out_file.write(line)
tag = '"meta": ['
lines_to_write = []
tag_found = False
with open('file.in',encoding="utf8") as in_file:
for line in in_file:
if line.strip() == tag:
tag_found = True
if tag_found:
lines_to_write.append(line)
with open('file.out','w',encoding="utf8") as out_file:
out_file.writelines(lines_to_write)
您的 tag_found 始終為 False:
tag = '"meta": ['
tag_found = False
with open('file.in',encoding="utf8") as in_file:
with open('file.out','w',encoding="utf8") as out_file:
for line in in_file:
if not tag_found and line.strip() == tag:
tag_found = True
continue
if tag_found:
out_file.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.