Reputation: 133
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
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
Reputation: 226231
The first function expects a file object and the second expects a string.
Hope this helps :-)
Upvotes: 1