【问题标题】:How to remove all lines from text file up until specific string?如何从文本文件中删除所有行,直到特定字符串?
【发布时间】:2022-01-19 00:52:15
【问题描述】:

在我需要的数据之前,我有一个包含大量调试信息的文本文件。我正在使用 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)

【问题讨论】:

    标签: python python-3.x line


    【解决方案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)
    

    【讨论】:

    • 此解决方案将标记之前的所有内容写入输出文件,然后标记之后没有任何内容。 IE。与我正在寻找的相反。 :-)
    • 啊,做到了。谢谢!
    【解决方案2】:

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

    【讨论】:

    • 抱歉,我尝试使用的代码链接错误。修复。无论如何,尝试了您的解决方案,但得到相同的空输出文件。
    猜你喜欢
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多