[英]How to remove all lines from text file up until specific string?
I have a text file that has a lot of debug information in it, prior to the data I need.我有一个文本文件,里面有很多调试信息,在我需要的数据之前。 I'm using python3 to attempt to rewrite the output so the file starts with a specific JSON tag.我正在使用 python3 尝试重写输出,以便文件以特定的 JSON 标记开头。 I attempted to use this solution Remove string and all lines before string from file but I'm getting an empty output file so I assume it's not finding the JSON tag.我试图使用这个解决方案Remove string and all lines before string from file但我得到一个空的输出文件,所以我认为它没有找到 JSON 标签。
Here is my code:这是我的代码:
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)
your tag_found is always False:您的 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.