Felix Huber
Felix Huber

Reputation: 133

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

[[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?

Upvotes: 2

Views: 79

Answers (2)

Rithin Chalumuri
Rithin Chalumuri

Reputation: 1839

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

Upvotes: 1

Raymond Hettinger
Raymond Hettinger

Reputation: 226231

The load() should be loads().

The first function expects a file object and the second expects a string.

Hope this helps :-)

Upvotes: 1

Related Questions