简体   繁体   English

如何从文本文件中删除所有行直到特定字符串?

[英]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.我正在使用 python3 尝试重写输出,以便文件以特定的 JSON 标记开头。 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.我试图使用这个解决方案Remove string and all lines before string from file但我得到一个空的输出文件,所以我认为它没有找到 JSON 标签。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文本文件中删除特定行? - How to remove specific lines from a text file? python - 如何从包含特定字母表的大型文本文件(> 60GB)中删除所有行? - How to remove all lines from a large text file (>60GB) that contains a specific alphabet in python? Python - 如何从文本文件中读取多行作为字符串并删除所有编码? - Python - How to read multiple lines from text file as a string and remove all encoding? 在特定字符串之后从文本文件中删除多行,然后替换为新文本 - Remove multiple lines from a text file after a specific string, then replace with new text 如何从文件中删除行直到特定字符? [Python] - How to delete lines from a file until a specific character? [Python] 如何从文本文件中将特定数量的行输入到数组中,并重复该操作,直到使用完所有行 - How to input an specific amount of lines from a text file into an array and repeat the action untill all lines are used 删除文件中的所有行,直到与字符串一致 - Delete all lines in file until line with string 从文本文件字符串中删除特定字符 - remove specific characters from text file string 从文件python中删除字符串和字符串之前的所有行 - remove string and all lines before string from file python 如何循环直到从文件中读取所有行? - How to loop until all lines read from a file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM