B
B
blackbb2018-11-11 19:35:40
Django
blackbb, 2018-11-11 19:35:40

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

2 answer(s)
N
neatsoft, 2018-11-11
@blackbb

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

K
Konstantin Malyarov, 2018-11-11
@Konstantin18ko

JSON

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question