简体   繁体   English

从 python 中读取具有多个列表列表的文件

[英]Reading a file with multiple list of lists from into python

This question is very similar to Reading a list of lists from a file as list of lists in python , except that the file I have has multiple lines with list of lists, such as这个问题非常类似于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]]

Following the advice from above link, my below attempt failed按照上述链接的建议,我的以下尝试失败了

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

throws the error抛出错误

--> 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'

What am I doing wrong?我究竟做错了什么?

The load() should be loads() . load()应该是loads()

The first function expects a file object and the second expects a string.第一个 function 需要一个文件 object 而第二个需要一个字符串。

Hope this helps:-)希望这可以帮助:-)

import json

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

print(result)

Outputs:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM