0

I have a file output.txt who's contents are already in a python dictionary format:

output.txt = {'id':123, 'user': 'abc', 'date':'20-08-1998'}

When I read the file into python I get the following:

f = open('output.txt','r', encoding='utf8')
print(f)
>>> <_io.TextIOWrapper name='output.txt' mode='r' encoding='utf8'>

How can I read the file in as a python dictionary?

I have tried to use the dict() constructor, but I get this error:

f = dict(open('output.txt','r', encoding='utf8'))
ValueError: dictionary update sequence element #0 has length 15656; 2 is required
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
PyRsquared
  • 6,970
  • 11
  • 50
  • 86
  • 2
    Use `ast.literal_eval()`. But really it would have been better to save this as JSON in the first place. – Daniel Roseman Mar 09 '18 at 15:36
  • open returns a wrapper, not the contents of a file, so you cannot call directly dict to it. Instead you will need to read the lines to get the content –  Mar 09 '18 at 15:38

1 Answers1

0

You can use the json module:

with open('output.txt', 'r') as f:
    my_dict = json.loads(f.read())

However JSON requires double quotes, so this wouldn't work for your file. A work around would be to use replace():

with open('output.txt', 'r') as f:
    my_dict = json.loads(f.read().replace("'", '"')

print(my_dict)
#{u'date': u'20-08-1998', u'id': 123, u'user': u'abc'}
pault
  • 41,343
  • 15
  • 107
  • 149