如何在.txt文件中读取字典? [重复]

时间:2022-10-29 13:33:51

This question already has an answer here:

这个问题在这里已有答案:

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

我有一个文件output.txt谁的内容已经是python字典格式:

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

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

当我将文件读入python时,我得到以下内容:

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?

如何以python字典的形式读取文件?

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

我试过使用dict()构造函数,但是我得到了这个错误:

f = dict(open('output.txt','r', encoding='utf8'))
ValueError: dictionary update sequence element #0 has length 15656; 2 is required

1 个解决方案

#1


0  

You can use the json module:

您可以使用json模块:

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

但是JSON需要双引号,因此这对您的文件不起作用。解决方法是使用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'}

#1


0  

You can use the json module:

您可以使用json模块:

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

但是JSON需要双引号,因此这对您的文件不起作用。解决方法是使用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'}