当前位置: 首页 > article >正文

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。这些操作在数据处理、配置文件转换、数据导入导出等任务中非常常用。


http://www.kler.cn/news/306444.html

相关文章:

  • 安卓获取apk的公钥,用于申请app备案等
  • Windows 11上pip报‘TLS/SSL connection has been closed (EOF) (_ssl.c:1135)‘的解决方法
  • MySQL一:在Ubuntu下安装MySQL数据库
  • UAC2.0 麦克风——单通道 USB 麦克风
  • C++部分题目解析
  • 基于ssm+vue+uniapp的智能停车场管理系统小程序
  • Chrome 本地调试webrtc 获取IP是xxx.local
  • SQL进阶技巧:火车票相邻座位预定一起可能情况查询算法 ?
  • 喜报 | 知从科技荣获 “AutoSec 安全之星 - 优秀汽车软件供应链安全方案奖”
  • Qt:Q_GLOBAL_STATIC实现单例(附带单例使用和内存管理)
  • 有了数据中台,是否需要升级到数据飞轮?怎么做才能升级到数据飞轮?
  • 并行编程实战——TBB中的Task
  • C++的内存分布
  • FastAPI与环境变量:实现无缝切换与高效运维
  • Python操作MySQL
  • 常见生成模型有哪些?生成模型前后存在依赖关系,怎么处理更合适
  • 二分算法——优选算法
  • 排队免单模式小程序开发
  • Harmony OS DevEco Studio低代码开发流程 - HarmonyOS开发自学5
  • 【Linux进程】Linux Shell编程实战:构建简易脚本示例与技巧详解
  • Unity3D 小案例 像素贪吃蛇 02 蛇的觅食
  • Oracle EBS中AR模块的财务流程概览
  • 安全API
  • 综合案例-数据可视化-柱状图
  • python 读取excel数据存储到mysql
  • JVM 运行时数据区域
  • Amazon EC2:引领企业迈向云计算的未来
  • Lua 拷贝
  • 本地调试spark,访问kerberos鉴权的hdfs、hive
  • SOEX解锁Web3社交软件的无限可能