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

标签 python python-3.x line

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

最佳答案

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)

关于python - 如何从文本文件中删除直到特定字符串的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52636019/

相关文章:

python - 将最佳拟合及其方程放入绘图中

python - 如何在 Python 中为 OpenCV minMaxLoc 函数创建掩码矩阵变量?

python - 查找两个字符串之间的共同字符

silverlight - 从Silverlight RichTextBox获取行数?

javascript - 如何仅围绕中点旋转一条线?

python - 使用 python 在文件中查找与关键字相关的值

python - ImportError:没有名为_______的模块

python - 如果我删除 Python 字典类中不存在的键会发生什么?

python - 按列值将 CSV 文件分类为不同的 CSV

java - "Flying past"在线算法?