0

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()))

2 Answers2

2

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()))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Perfect! Thanks for helping. I'm trying to make my prof's homework when i pass this hw he take me to his project. I wasn't know python. I'm studying for 4 days. Hw is : we have a text file (json) and we should read this json file each 1 min and we have to put the buffer(array etc) and each 5 min we have to delete the oldest data. When the buffer overflowed we should to solve this. Json format should be like : imei,hw_version,sw_version,device_type how can i put this variebles to array? – Jonathan Georgelous Oct 19 '16 at 04:02
1

I tried to come up with a more elegant solution that doesn't use regular expressions, but everything I came up with is far more verbose, so try this:

import re

d = {}
with open('test.txt') as f:
    for line in f:
        k, v = re.findall(r'"(.+?)"', line)
        d[k] = v

print(d)

re.findall(r'\"(.+?)\"', line) will return all the matches where text is within quotes on each line, and assign the first match to k and the second to v. These are then used as keys and values in a dictionary d. Assuming that the format of your text file is constant, this should give you the result you are looking for.

Note that the order of the dictionary will likely be different than your text file, but that shouldn't matter since it is a dictionary.

elethan
  • 16,408
  • 8
  • 64
  • 87