【问题标题】:How to read in a .txt file as a dictionary? [duplicate]如何将 .txt 文件作为字典读取? [复制]
【发布时间】:2018-03-09 15:32:45
【问题描述】:

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

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

当我将文件读入 python 时,我得到以下信息:

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

如何将文件作为 python 字典读取?

我曾尝试使用dict() 构造函数,但出现此错误:

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

【问题讨论】:

  • 使用ast.literal_eval()。但实际上,首先将其保存为 JSON 会更好。
  • open 返回一个包装器,而不是文件的内容,因此您不能直接调用 dict 。相反,您需要阅读这些行以获取内容

标签: python file dictionary text


【解决方案1】:

您可以使用json 模块:

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

但是JSON requires double quotes,所以这不适用于您的文件。解决方法是使用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'}

【讨论】:

    猜你喜欢
    • 2020-06-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多