如何从文本文件中删除特定字符串之前的所有行?

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_found总是错误的:

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)
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)