Issue
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. 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.
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)
Solution
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)
Answered By - PMende
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.