You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取XML指定字段写入带表头CSV文件的方法

实现方法

csv(Python内置,无需额外安装)和pandas(第三方数据处理库)都可以实现带表头的CSV写入需求,两种实现方式如下:

方法1:使用内置csv库(推荐,无额外依赖)

不要手动拼接逗号字符串生成CSV——如果后续字段内容里包含逗号,会直接导致CSV格式错乱,用标准库的csv写入模块会自动处理特殊字符转义,代码基于你已有的逻辑修改即可:

import xml.etree.ElementTree as ET
import csv

parse_xml = ET.parse('/content/sample_data/xyz.xml')
get_root_element = parse_xml.getroot()

# 写入CSV,newline=''是csv模块官方要求的参数,避免生成多余空行
with open('menu_output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    csv_writer = csv.writer(csv_file)
    # 先写入指定表头
    csv_writer.writerow(['price', 'name', 'calories'])
    # 遍历XML节点逐行写入数据
    for row_node in get_root_element.findall('row'):
        price = row_node.find('price').text
        name = row_node.find('name').text
        calories = row_node.find('calories').text
        csv_writer.writerow([price, name, calories])

运行后会在脚本运行目录生成menu_output.csv文件,自带要求的三列表头。

方法2:使用pandas库(适合后续需要做数据处理的场景)

如果你的环境已经安装了pandas,可以用更简洁的方式写入,后续做数据筛选、计算也更方便:

import xml.etree.ElementTree as ET
import pandas as pd

parse_xml = ET.parse('/content/sample_data/xyz.xml')
get_root_element = parse_xml.getroot()

# 收集所有行数据
result = []
for row_node in get_root_element.findall('row'):
    result.append({
        'price': row_node.find('price').text,
        'name': row_node.find('name').text,
        'calories': row_node.find('calories').text
    })

# 转DataFrame写入CSV,index=False用于取消pandas默认生成的行号列
df = pd.DataFrame(result)
df.to_csv('menu_output_pd.csv', index=False, encoding='utf-8')

注意:运行代码前请确认XML文件的路径和代码中填写的路径一致,避免报文件不存在的错误。

内容的提问来源于stack exchange,提问作者kiric8494

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:24:24