Answer the question
In order to leave comments, you need to log in
How to read dictionary from text file?
Hello, there is a text file with the following content:
{'country': 'Russia', 'city': 'Moscow'};
{'country': 'Turkey', 'city': 'Istanbul'};
etc.
This data must be read and written to the site database. Model with country and city fields. How to read such data format correctly?
Answer the question
In order to leave comments, you need to log in
This is not json, because json uses double quotes. You can read such data using the ast module :
#!/usr/bin/env python3
import ast
filename = 'file.txt'
# open file
with open(filename) as f:
# read lines one by one
for line in f:
# remove semicolon and new line characters from the end of the line
line = line.rstrip('\n;')
# parse string
data = ast.literal_eval(line)
# print representation of the data
print(repr(data))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question