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

3
我有一个文本文件,里面有很多我需要的数据之前的调试信息。我正在尝试使用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)
2个回答

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

这个解决方案将标签之前的所有内容写入输出文件,然后标签之后的内容则不会被写入。也就是说,与我所期望的相反。 :-) - timsterc
啊,就是这样。谢谢! - timsterc

1

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

1
抱歉,我之前使用的代码链接有误,已经修复。无论如何,我尝试了你提供的解决方案,但是输出文件仍然为空。 - timsterc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接