批量将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—sofile.txtbecomesfile.csv,data.jsonbecomesdata.csv, no manual filename editing needed. - Robust CSV formatting: Uses Python's built-in
csv.DictWriterinstead of manually concatenating strings. This fixes hidden bugs (like commas in yourvaluefield 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
相关产品推荐
相关产品推荐

