Berkay Ezdemir Berkay Ezdemir - 1 month ago 11
Python Question

Python How can i read text file like dictionary

I hava a text file like this :

"imei": "123456789",
"sim_no": "+90 xxx xxx xx xx",
"device_type": "standart",
"hw_version": "1.01",
"sw_version": "1.02"


and i want read this file like dictionary. I mean, when i write imei it should give me 123456789. I'm creating free dictionary and i'm reading this file but its reading like string.

file=open("test.txt","r")

buffer={}
print(type(buffer))
buffer=file.read()
print(type(buffer))

<class 'dict'>
<class 'str'>


EDIT : Problem is solved.

import json

with open("test.txt") as f:
mydict = json.loads('{{ {} }}'.format(f.read()))

Answer

Use the json module; you've already got legal JSON aside from missing the outer curly braces:

import json

with open("test.txt") as f:
    mydict = json.loads('{{ {} }}'.format(f.read()))
Comments