- 将包含字典的列表转换为JSON格式字符串并写入文件:
import json
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
# 转换为JSON格式字符串
json_data = json.dumps(data, indent=4)
# 写入文件
with open('data.json', 'w') as file:
file.write(json_data)
- 从JSON文件读取数据并转换为CSV格式保存到另一个文件:
import json
import csv
# 从JSON文件读取数据
with open('data.json', 'r') as file:
json_data = json.load(file)
# 准备CSV数据
csv_data = []
headers = list(json_data[0].keys())
for item in json_data:
csv_data.append(list(item.values()))
# 写入CSV文件
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headers)
writer.writerows(csv_data)