0

I have a text file with dictionary representations. These are opened into python as strings and I want to convert them to dicts using ast.literal_eval

I found the following thread which helped get me so far. Python: error parsing strings from text file with Ast module

I am wondering if the source string is invalid as mentioned in this thread but I don't know how to check this. ast.literal_eval: SyntaxError: unexpected EOF while parsing

data in output file

{'name': 'John', 'age': '21'}
{'name': 'Mary', 'age': '23'}

code

from ast import literal_eval

output_file = 'profiles.txt'

try:
    with open(output_file) as f:
        for entry in f:
            entry_dict = literal_eval(entry)
            print(entry_dict)
except Exception as e:
    print(e)

My desired result is to have the strings as class 'dict' which actually works but is followed by the following stack trace

<class 'dict'>
<class 'dict'>
Traceback (most recent call last):
  File "write_site_to_netbox.py", line 25, in <module>
    site_dict = literal_eval(site_entry)
  File "/usr/lib/python3.6/ast.py", line 48, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib/python3.6/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1

    ^
SyntaxError: unexpected EOF while parsing
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Barry Keegan
  • 81
  • 2
  • 9

0 Answers0