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

批量将JSON文件转换为对应CSV文件的Python代码求助

Solution for Batch JSON-to-CSV Conversion with File Output

Got it, let's get your code working to batch process all those JSON files and save each to its own CSV—no more console-only output. Your current code is already looping through files, it just needs to write to disk instead of printing, plus a few tweaks for robustness and cleaner style.

Here's the revised code:

import json
import csv
import os

# Replace this with your full list of files, or use the auto-detect trick below
file_list = ['file.txt', 'file2.txt']

for filename in file_list:
    # Generate matching CSV filename (safely replaces input extension with .csv)
    csv_filename = os.path.splitext(filename)[0] + '.csv'
    
    # Load the JSON data from the input file
    with open(filename, 'r') as json_file:
        distros_dict = json.load(json_file)
    
    # Write the converted data to the CSV file
    with open(csv_filename, 'w', newline='') as csv_file:
        # Define CSV headers to match your JSON fields
        fieldnames = ['timestamp', 'value']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        
        # Write the header row first
        writer.writeheader()
        
        # Loop through each entry in the JSON array and write to CSV
        for distro in distros_dict:
            writer.writerow({
                'timestamp': distro['timestamp'],
                'value': distro['value']
            })
    
    # Optional progress update for large batches
    print(f"Converted {filename} → {csv_filename}")

Key improvements explained:

  • Automatic CSV naming: Uses os.path.splitext() to safely swap the input file's extension for .csv—so file.txt becomes file.csv, data.json becomes data.csv, no manual filename editing needed.
  • Robust CSV formatting: Uses Python's built-in csv.DictWriter instead of manually concatenating strings. This fixes hidden bugs (like commas in your value field breaking the CSV structure) and keeps the code clean.
  • Cleaner looping: Replaced clunky range(len(file_list)) with direct iteration over the file list—easier to read and maintain.
  • Progress tracking: The print statement lets you monitor which files are done, perfect for batches of hundreds of files.

Bonus: Auto-detect all JSON files in a folder

If you don't want to manually list every file, use glob to grab all relevant files automatically:

import glob

# Replace './your-folder' with your target directory (use '.' for the current folder)
# Adjust the extension to .json if your files use that instead of .txt
file_list = glob.glob('./your-folder/*.txt')

This will pull every .txt (JSON) file in the specified folder, so you don't have to type hundreds of filenames by hand.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:46:02