Python--常见的数据格式转换

下面是几个常见的数据格式转换的示例,涵盖了一些常用的格式,如 CSV、XML、YAML 等。每个示例都会介绍如何从一种格式转换到另一种格式。

1. CSV 转 JSON

CSV 文件通常以逗号分隔,行代表记录,列代表字段。我们可以使用 csvjson 模块来实现转换。

示例代码
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: John
    age: 30
    city: New York
  - name: Jane
    age: 25
    city: 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: 30
  city: New York
  name: John
- age: 25
  city: Los Angeles
  name: Jane

总结

这些示例展示了如何在不同常见数据格式之间进行转换,包括 CSV、JSON、XML 和 YAML。这些操作在数据处理、配置文件转换、数据导入导出等任务中非常常用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值