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