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

如何删除包含指定键值对的JSON文件?解决代码索引报错

解决方法

先给你捋清楚代码里的问题:

  • 两段代码都搞混了文件名和文件内容:比如第二段直接用json.loads(file),但file是文件名,不是文件里的JSON文本,肯定解析失败;第一段里的filepath是固定字符串,应该用循环里的file变量。
  • 解析后的JSON是字典不是列表:你用for file in data遍历字典时,拿到的是字典的键(比如"error"这种字符串),所以file['error']就会报"string indices must be integers"——字符串不能用字典的键来索引。

下面是修正后的可用代码:

import json
import os

# 假设你的fileList是目录里所有JSON文件的路径列表
for file_path in fileList:
    try:
        # 打开文件并解析JSON
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)  # 用json.load比loads+read更简洁
        
        # 判断是否符合要删除的条件
        if data.get('error') == 'not_found' and data.get('message') == "Can't find" and data.get('value') == 'item':
            os.remove(file_path)
            print(f"已删除文件: {file_path}")
    except (json.JSONDecodeError, FileNotFoundError):
        # 处理JSON解析失败或者文件找不到的情况
        print(f"跳过异常文件: {file_path}")

关键细节:

  • 用json.load(f)直接从文件对象解析JSON,比json.loads(f.read())更高效
  • 用data.get('error')而非data['error'],避免JSON里没有error键时抛出KeyError
  • 加上异常处理,防止遇到非JSON格式或损坏的文件导致程序崩溃
  • 必须用循环里的file_path变量,不能写死固定字符串"filepath"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:31:00