-2

So I have a text file with the text below: {'Maps': {'Usefulness':80,'Accesibility':70,'Popularity':90} (the dictionary carries on that's why there may be a few syntax issues) How do I convert this text into python code inside my program? eg: if the text files name is x.txt

textfile = convert(x.txt)
print(list(textfile.keys()))

the output would look something like

['Maps','Drive','Chrome']
Readraid
  • 41
  • 4

2 Answers2

0

You should use the json module

import json

with open('x.txt') as json_file:
    data = json.load(json_file)

print(data.keys)
NirO
  • 216
  • 2
  • 12
0

You can use ast.literal_eval to evaluate a string (like the one you get from reading a text file) as Python code:

import ast
s = """{
    'Maps': {
        'Usefulness':80,
        'Accesibility':70,
        'Popularity':90
        }
    }"""
ast.literal_eval(s)
# output: {'Maps': {'Usefulness': 80, 'Accesibility': 70, 'Popularity': 90}}

Reading from a text file:

with open('file.txt', 'r') as file:
    result = ast.literal_eval(file.read())
print(list(result.keys()))

If your text file is just a dictionary you can also use the json module. But the more generalist answer is to use ast.literal_eval.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25