import json
import csv
def json_to_csv(file_path):
try:
with open(file_path, 'r') as json_file:
json_data = json.load(json_file)
except json.decoder.JSONDecodeError:
print(f"{file_path} is not a valid json file.")
return
csv_file_path = file_path.replace('.json', '.csv')
with open(csv_file_path, 'w', newline='') as csv_file:
fieldnames = json_data[0].keys()
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for row in json_data:
writer.writerow(row)
print(f'{file_path} has been converted to {csv_file_path}')
写python代码,读取文件并检查是否为json,如果是将json转化为csv代码,否则输出不规范文件...
最新推荐文章于 2024-10-17 11:22:54 发布