【发布时间】: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