簡體   English   中英

從 python 中讀取具有多個列表列表的文件

[英]Reading a file with multiple list of lists from into 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'

我究竟做錯了什么?

load()應該是loads()

第一個 function 需要一個文件 object 而第二個需要一個字符串。

希望這可以幫助:-)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM