从python中读取包含多个列表的文件

2024-04-19 01:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题与Reading a list of lists from a file as list of lists in python非常相似,只是我的文件有多行列表,例如

[[1,2,3],[4,5]]
[[1], [4], [6], [1,2,3]]
[[]]
[[1,5]]

按照上面链接的建议,我下面的尝试失败了

import json
f = open('idem_perms.txt', 'r')
for line in f:
    e = json.load(line)

抛出错误

--> 287     return loads(fp.read(),
    288         encoding=encoding, cls=cls, object_hook=object_hook,
    289         parse_float=parse_float, parse_int=parse_int,

AttributeError: 'str' object has no attribute 'read'

我做错什么了?你知道吗


Tags: ofinjsonreadobjectparselinehook
2条回答
import json

with open('idem_perms.txt', 'r') as file:
    result = [json.loads(line) for line in file.readlines()]

print(result)

输出:

[[[1, 2, 3], [4, 5]], [[1], [4], [6], [1, 2, 3]], [[]], [[1, 5]]]

^{}应该是^{}。你知道吗

第一个函数需要一个文件对象,第二个函数需要一个字符串。你知道吗

希望这有帮助:-)

相关问题 更多 >