Python--常见的数据格式转换
下面是几个常见的数据格式转换的示例,涵盖了一些常用的格式,如 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 格式。
示例代码
import json import csv# 定义输入和输出文件路径 json_file = 'data.json' csv_file = 'output.csv'def json_to_csv(json_file, csv_file):with open(json_file, 'r', encoding='utf-8') as infile:data = json.load(infile)# 提取字段名(假设所有 JSON 对象都有相同的字段)fieldnames = data[0].keys()# 将数据写入 CSV 文件with open(csv_file, 'w', newline='', encoding='utf-8') as outfile:writer = csv.DictWriter(outfile, fieldnames=fieldnames)writer.writeheader()writer.writerows(data)print(f"JSON to CSV conversion complete! Output saved to {csv_file}")# 调用函数 json_to_csv(json_file, csv_file)
示例输入(JSON 文件 data.json
)
[{"name": "John", "age": 30, "city": "New York"},{"name": "Jane", "age": 25, "city": "Los Angeles"} ]
输出(CSV 文件 output.csv
)
name,age,city John,30,New York Jane,25,Los Angeles
3. XML 转 JSON
XML 是一种常用于数据交换的格式,Python 中可以使用 xmltodict
模块来处理 XML 数据并转换为 JSON。
示例代码
import xmltodict import json# 定义输入和输出文件路径 xml_file = 'data.xml' json_file = 'output.json'def xml_to_json(xml_file, json_file):# 读取 XML 文件with open(xml_file, 'r', encoding='utf-8') as infile:xml_content = infile.read()data_dict = xmltodict.parse(xml_content) # 将 XML 转换为字典# 将字典写入 JSON 文件with open(json_file, 'w', encoding='utf-8') as outfile:json.dump(data_dict, outfile, indent=4, ensure_ascii=False)print(f"XML to JSON conversion complete! Output saved to {json_file}")# 调用函数 xml_to_json(xml_file, json_file)
示例输入(XML 文件 data.xml
)
<people><person><name>John</name><age>30</age><city>New York</city></person><person><name>Jane</name><age>25</age><city>Los Angeles</city></person> </people>
输出(JSON 文件 output.json
)
{"people": {"person": [{"name": "John","age": "30","city": "New York"},{"name": "Jane","age": "25","city": "Los Angeles"}]} }
4. YAML 转 JSON
YAML 是一种简洁的配置文件格式。可以使用 PyYAML
库将 YAML 文件转换为 JSON 文件。
示例代码
import yaml import json# 定义输入和输出文件路径 yaml_file = 'data.yaml' json_file = 'output.json'def yaml_to_json(yaml_file, json_file):# 读取 YAML 文件with open(yaml_file, 'r', encoding='utf-8') as infile:data = yaml.safe_load(infile) # 将 YAML 加载为 Python 字典# 将字典写入 JSON 文件with open(json_file, 'w', encoding='utf-8') as outfile:json.dump(data, outfile, indent=4, ensure_ascii=False)print(f"YAML to JSON conversion complete! Output saved to {json_file}")# 调用函数 yaml_to_json(yaml_file, json_file)
示例输入(YAML 文件 data.yaml
)
people:- name: Johnage: 30city: New York- name: Janeage: 25city: Los Angeles
输出(JSON 文件 output.json
)
{"people": [{"name": "John","age": 30,"city": "New York"},{"name": "Jane","age": 25,"city": "Los Angeles"}] }
5. JSON 转 YAML
可以使用 PyYAML
库将 JSON 文件转换为 YAML 文件。
示例代码
import json import yaml# 定义输入和输出文件路径 json_file = 'data.json' yaml_file = 'output.yaml'def json_to_yaml(json_file, yaml_file):# 读取 JSON 文件with open(json_file, 'r', encoding='utf-8') as infile:data = json.load(infile)# 将数据写入 YAML 文件with open(yaml_file, 'w', encoding='utf-8') as outfile:yaml.dump(data, outfile, allow_unicode=True)print(f"JSON to YAML conversion complete! Output saved to {yaml_file}")# 调用函数 json_to_yaml(json_file, yaml_file)
示例输入(JSON 文件 data.json
)
{"people": [{"name": "John","age": 30,"city": "New York"},{"name": "Jane","age": 25,"city": "Los Angeles"}] }
输出(YAML 文件 output.yaml
)
people: - age: 30city: New Yorkname: John - age: 25city: Los Angelesname: Jane
总结
这些示例展示了如何在不同常见数据格式之间进行转换,包括 CSV、JSON、XML 和 YAML。这些操作在数据处理、配置文件转换、数据导入导出等任务中非常常用。