下面是几个常见的数据格式转换的示例,涵盖了一些常用的格式,如 CSV、XML、YAML 等。每个示例都会介绍如何从一种格式转换到另一种格式。
1. CSV 转 JSON
CSV 文件通常以逗号分隔,行代表记录,列代表字段。我们可以使用 csv 和 json 模块来实现转换。
示例代码
import csv
import json
# 定义输入和输出文件路径
csv_file = 'data.csv'
json_file = 'output.json'
def csv_to_json(csv_file, json_file):
data = []
# 读取 CSV 文件并转换为字典列表
with open(csv_file, mode='r', encoding='utf-8') as infile:
reader = csv.DictReader(infile)
for row in reader:
data.append(row)
# 将字典列表写入 JSON 文件
with open(json_file, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, indent=4, ensure_ascii=False)
print(f"CSV to JSON conversion complete! Output saved to {json_file}")
# 调用函数
csv_to_json(csv_file, json_file)
示例输入(CSV 文件 data.csv)
name,age,city John,30,New York Jane,25,Los Angeles
输出(JSON 文件 output.json)
[
{
"name": "John",
"age": "30",
"city": "New York"
},
{
"name": "Jane",
"age": "25",
"city": "Los Angeles"
}
]
2. JSON 转 CSV
从 JSON 文件转换为 CSV 文件,可以使用 Python 的 csv 模块写出 CSV 格式。<

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



