简体   繁体   中英

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

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 = '"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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM