You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取多行列表的列表文件时json.load报错,问题出在哪?

解决Python读取文件中列表列表的JSON解析错误

嗨,这个问题其实很好梳理,咱们一步步来解决:

错误原因:用错了JSON解析方法

你遇到的AttributeError: 'str' object has no attribute 'read',核心是混淆了json.load()和json.loads()的用法:

  • json.load():接收文件对象作为参数,它会自动读取文件内容并解析。
  • json.loads():接收字符串作为参数,用来解析内存中的JSON字符串。

你代码里的line是从文件中读取的字符串,给json.load()传字符串肯定会报错,因为字符串没有read()方法——这个方法是文件对象才有的。

基础修正:替换为json.loads()

如果你的文件每一行是单个合法的JSON结构(比如一行只有[[1,2,3],[4,5]]),那把代码改成这样就能正常运行:

import json

# 用with语句自动管理文件,比直接open更安全
with open('idem_perms.txt', 'r') as f:
    for line in f:
        # 先去掉行首尾的空白(换行、空格等),避免解析报错
        cleaned_line = line.strip()
        # 跳过空行
        if not cleaned_line:
            continue
        # 用loads处理字符串
        parsed_data = json.loads(cleaned_line)
        print(parsed_data)

进阶处理:一行包含多个JSON结构的情况

看你给出的例子,文件里的行是多个列表列表用空格分隔的(比如[[1,2,3],[4,5]] [[1], [4], [6], [1,2,3]] [[]] [[1,5]]),这种整行不是合法的JSON(JSON不允许多个顶级结构),直接用loads()会报错。这时候可以用json.JSONDecoder来逐个解析行内的每个JSON结构:

import json

with open('idem_perms.txt', 'r') as f:
    for line in f:
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        
        decoder = json.JSONDecoder()
        current_pos = 0
        line_length = len(cleaned_line)
        
        # 循环解析行内的每个JSON结构
        while current_pos < line_length:
            try:
                # 解析从current_pos开始的JSON对象,返回解析结果和下一个起始位置
                data, current_pos = decoder.raw_decode(cleaned_line, current_pos)
                print(data)
                
                # 跳过结构之间的空格
                while current_pos < line_length and cleaned_line[current_pos].isspace():
                    current_pos += 1
            except json.JSONDecodeError:
                # 如果遇到无法解析的部分,跳过当前字符继续(可根据需求调整)
                current_pos += 1

这个方法能自动处理行内多个独立的JSON结构,不管它们之间用多少空格分隔。

内容的提问来源于stack exchange,提问作者Felix Huber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:23:19