Python3 不解压直接解析xml文件,并进行csv出力

本文介绍了如何在Python 3.7环境下,使用zipfile、csv、xml.dom.minidom等库,在不解压zip文件的情况下,筛选并解析xml文件,然后将数据写入csv文件。通过示例代码展示了解压缩过程,同时针对csv文件中文乱码问题给出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在有一个zip文件,里面有多个类型的文件,想要在不解压zip包的情况下筛选并解析其中的xml文件,并且将解析的数据出力到csv文件中。(利用Python提供的zipfile库)

宜人宜己,方便自己以后查找,也给大家提供一个思路吧。

Python环境:Python 3.7

IDE:JetBrains PyCharm

条件准备:在任意路径下放入需要进行读取的zip文件:

eg:在 E:\work 下有一个文件:E:\work\movies.zip

在zip文件中有一个movies文件夹,在\movies里面有多个文件,它们类型五花八门:

我们的目标就是要在不解压movies.zip的情况下,直接读取里面的person.xml和person2.xml,并将文件里面的数据进行csv出力。

person.xml文件:

<collection company="BBX">
<person project="项目一">
   <name>张三</name>
   <sex>男</sex>
   <age>25</age>
   <height>178</height>
   <weight>140</weight>
   <birthday>1994-07-22</birthday>
   <phone>13689457821</phone>
   <home>成都</home>
</person>
<person project="项目一">
   <name>李四</name>
   <sex>男</sex>
   <age>27</age>
   <height>164</height>
   <weight>110</weight>
   <birthday>1992-12-25</birthday>
   <phone>13683645821</phone>
   <home>上海</home>
</person>
<person project="项目二">
   <name>王倩</name>
   <sex>女</sex>
   <age>21</age>
   <height>170</height>
   <weight>100</weight>
   <birthday>1998-05-02</birthday>
   <phone>13689489461</phone>
   <home>北京</home>
</person>
<person project="项目二">
   <name>陈宇</name>
   <sex>男</sex>
   <age>24</age>
   <height>171</height>
   <weight>120</weight>
   <birthday>1995-04-25</birthday>
   <phone>13689489471</phone>
   <home>成都</home>
</person>
<person project="项目二">
   <name>何希美</name>
   <sex>女</sex>
   <age>23</age>
   <height>166</height>
   <weight>92</weight>
   <birthday>1996-06-12</birthday>
   <phone>13684857856</phone>
   <home>西安</home>
</person>
<person project="项目二">
   <name>杨俊</name>
   <sex>男</sex>
   <a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值