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

Python如何遍历文件夹所有文件并对每个文件执行自定义处理脚本

Python批量处理目录下JSON文件实现方案

你只需要引入Python内置的os模块实现目录遍历,将原有单文件处理逻辑封装为可复用函数,批量读取目标路径下的所有JSON文件即可,修改后的完整代码如下:

import json
import os

# 配置路径,可根据实际情况修改
INPUT_DIR = "./待处理JSON文件夹"  # 待处理文件所在的文件夹路径
OUTPUT_DIR = "./处理后结果"       # 处理完成的文件输出路径

# 自动创建输出文件夹,不存在则新建
os.makedirs(OUTPUT_DIR, exist_ok=True)

def process_single_json(input_path, output_path):
    # 读取原JSON文件
    with open(input_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    # 筛选entities不为空的数据
    data = [obj for obj in data if obj.get('entities')]
    # 重命名entities为labels
    for elem in data:
        elem['labels'] = elem.pop('entities')
    # 输出处理后的JSON
    with open(output_path, 'w', encoding='utf-8') as outfile:
        json.dump(data, outfile, ensure_ascii=False, indent=2)

# 遍历输入文件夹下的所有文件
for filename in os.listdir(INPUT_DIR):
    # 仅处理后缀为.json的文件
    if filename.lower().endswith('.json'):
        input_file_path = os.path.join(INPUT_DIR, filename)
        # 输出文件名添加_processed后缀,避免重名覆盖
        output_file_name = f"{os.path.splitext(filename)[0]}_processed.json"
        output_file_path = os.path.join(OUTPUT_DIR, output_file_name)
        # 执行单文件处理逻辑
        process_single_json(input_file_path, output_file_path)
        print(f"文件 {filename} 处理完成,结果已保存至 {output_file_path}")

补充说明

  • 递归处理子目录:如果需要遍历目标文件夹下所有嵌套子目录内的JSON文件,可将遍历逻辑替换为os.walk实现
  • 编码适配:代码默认使用utf-8编码读写文件,新增ensure_ascii=False参数避免中文乱码,若你的文件为其他编码可自行调整
  • 异常兼容:若存在格式损坏的JSON文件,可在process_single_json函数内添加try-except捕获异常,跳过损坏文件避免程序中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:06:02