Issue
I have .txt
file and its loaded with a lot of text but in between 2-3 paragraphs there is a text like dictionary:
somerandomtextinthisline
{"key1":"value1","key2":"value2"}
somerandomtextinthislineblasd
asbdjalsdnlasd
dasdjasdkjn
<space>
{"key1":"value1","key2":"value2"}
someranomtextaganinasdlasd
asdasd
So what I want to do is read the whole file and grab all 'key2'
from the file and paste it in a file called result.txt
.
How can I code this?
Solution
Use ast.literal_eval
to convert it to a dictionary (if possible) and check if the parsed line can be indexed using 'key2'
:
import ast
with open(filename) as fin:
for line in fin:
try:
parsed = ast.literal_eval(line)
key2 = parsed['key2']
except Exception:
continue
print(key2) # I just print it here, you probably need to write it to another file instead
Answered By - MSeifert
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.