如何修改Python脚本仅转换未生成CSV的JSON文件?
只转换未生成CSV的JSON文件的Python脚本修改方案
这问题太实用了,毕竟重复转换既浪费时间又没必要!核心思路就是遍历JSON文件时,先检查对应的CSV文件是否已经存在——不存在才执行转换。下面给你两种常见的实现方式,你可以根据自己的习惯选:
方式一:用传统的os模块实现
如果你的项目还在使用Python 3.4之前的版本,或者更习惯os模块的写法,可以用这个版本:
import os import json import csv # 目标目录(当前目录,也可以改成你需要的绝对路径) target_dir = os.getcwd() # 遍历目录下所有文件 for filename in os.listdir(target_dir): # 只筛选JSON格式的文件 if filename.endswith(".json"): # 生成对应的CSV文件名:替换原文件后缀为.csv csv_filename = os.path.splitext(filename)[0] + ".csv" csv_full_path = os.path.join(target_dir, csv_filename) # 关键判断:如果CSV文件不存在,才执行转换 if not os.path.exists(csv_full_path): print(f"正在转换:{filename} → {csv_filename}") # 读取JSON文件内容 with open(os.path.join(target_dir, filename), 'r', encoding='utf-8') as json_file: json_data = json.load(json_file) # 这里是JSON转CSV的核心逻辑(根据你的JSON结构调整) # 示例假设JSON是「列表套字典」的格式(最常见的场景) if json_data: # 获取所有字段名作为CSV表头 csv_fields = json_data[0].keys() # 写入CSV文件 with open(csv_full_path, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=csv_fields) writer.writeheader() writer.writerows(json_data) else: print(f"跳过:{csv_filename} 已存在,无需重复转换 {filename}")
方式二:用现代的pathlib模块实现(推荐)
Python 3.4+推出的pathlib模块让文件路径操作更简洁直观,代码可读性更高,非常推荐使用:
from pathlib import Path import json import csv # 目标目录(当前目录,也可以写成 Path("/your/target/dir")) target_dir = Path.cwd() # 遍历目录下所有JSON文件(**/*.json 可以递归遍历子目录) for json_file_path in target_dir.glob("*.json"): # 直接替换文件后缀生成CSV路径,一步到位 csv_file_path = json_file_path.with_suffix(".csv") # 关键判断:检查CSV是否已存在 if not csv_file_path.exists(): print(f"正在转换:{json_file_path.name} → {csv_file_path.name}") # 读取JSON内容 with open(json_file_path, 'r', encoding='utf-8') as f: json_data = json.load(f) # JSON转CSV逻辑(同样根据你的JSON结构调整) if json_data: csv_fields = json_data[0].keys() with open(csv_file_path, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=csv_fields) writer.writeheader() writer.writerows(json_data) else: print(f"跳过:{csv_file_path.name} 已存在,无需重复转换 {json_file_path.name}")
几个注意点:
- JSON结构适配:上面的示例假设你的JSON是「列表包含多个字典」的格式(比如数据库导出的JSON),如果你的JSON结构是单个对象、嵌套结构等,需要调整转换逻辑部分的代码。
- 递归处理子目录:如果需要处理子目录里的JSON文件,把
glob("*.json")改成glob("**/*.json", recursive=True)(Python 3.10+无需加recursive=True)。 - 异常处理:可以在代码里加上
try-except块,比如捕获JSON解析错误、文件读写错误,避免脚本中途崩溃。
内容的提问来源于stack exchange,提问作者supercontra
相关产品推荐
相关产品推荐

