【问题标题】:Reading a file with multiple list of lists from into python从python中读取具有多个列表列表的文件
【发布时间】:2020-02-25 22:33:33
【问题描述】:

这个问题和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'

我做错了什么?

【问题讨论】:

    标签: python import


    【解决方案1】:

    load() 应该是 loads()。

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

    希望这会有所帮助:-)

    【讨论】:

      【解决方案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]]]
      

      【讨论】:

        猜你喜欢
        • 2014-04-10
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2016-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多