使用Python将XML转换为CSV格式的方法
发布时间:2023-12-11 17:38:50
在Python中,我们可以使用xml.etree.ElementTree模块来解析XML文件,并使用csv模块将解析后的数据写入CSV文件。
下面是一个将XML转换为CSV的方法及使用示例:
1. 导入所需模块:
import xml.etree.ElementTree as ET import csv
2. 定义函数xml_to_csv来实现XML到CSV的转换:
def xml_to_csv(xml_file, csv_file):
tree = ET.parse(xml_file)
root = tree.getroot()
with open(csv_file, 'w', newline='') as f:
csv_writer = csv.writer(f)
# 写入CSV文件的表头
csv_writer.writerow(['Name', 'Age', 'Gender'])
# 遍历XML文件的每个子元素
for person in root.findall('person'):
name = person.find('name').text
age = person.find('age').text
gender = person.find('gender').text
# 将数据写入CSV文件的每一行
csv_writer.writerow([name, age, gender])
3. 假设有如下的XML文件data.xml:
<people>
<person>
<name>John</name>
<age>25</age>
<gender>Male</gender>
</person>
<person>
<name>Lisa</name>
<age>30</age>
<gender>Female</gender>
</person>
...
</people>
4. 调用xml_to_csv函数将XML文件转换为CSV文件output.csv:
xml_to_csv('data.xml', 'output.csv')
执行后,将生成一个名为output.csv的CSV文件,其内容如下:
Name,Age,Gender John,25,Male Lisa,30,Female ...
以上就是使用Python将XML转换为CSV格式的方法及示例。你可以根据实际情况,修改代码以适应不同的XML结构和字段需求。
