从文本文件中删除所有行,直到特定的字符串-python3

时间:2018-10-03 21:36:43

标签: python python-3.x line

在我需要的数据之前,我有一个文本文件,其中包含许多调试信息。我正在使用python3尝试重写输出,以便文件以特定的json标签开头。我尝试使用此解决方案remove string and all lines before string from file python,但是我得到的输出文件为空,因此我认为它没有找到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)

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

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