前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用Python进行XML转CSV

利用Python进行XML转CSV

作者头像
py3study
发布2020-01-08 19:49:39
1.4K0
发布2020-01-08 19:49:39
举报
文章被收录于专栏:python3

#!/usr/bin/python

#XMLtoCSV.py

#encoding:utf-8

import csv, os

from xml.dom.minidom import parse

def createCSVFile(filePrefix):

    csvFile = open(filePrefix+'.csv', 'wb')  #注意是二进制写入,否则会有多余空格

    csvWriter = csv.writer(csvFile)

    bWriteHead = False

    xmlFile = open(filePrefix+'.xml')

    domTree = parse(xmlFile)

    #print domTree

    root = domTree.documentElement

    #print dir(collection)

    for node in root.childNodes:

        if node.nodeType == node.ELEMENT_NODE:

            #print node.nodeName

            element = {}

            for key in node.attributes.keys():

                value = node.attributes.get(key).value

                element[key] = value

            if len(element) > 0:

                if bWriteHead == False:

                    csvWriter.writerow(tuple(element.keys()))

                    bWriteHead = True

                csvWriter.writerow(tuple(element.values()))

            else:

                print node.attributes

   

csvFile.close()

    xmlFile.close()

def main():

    for root, dirs, files in os.walk(os.getcwd()):

        print root, dirs, files

        for fname in files:

            index = fname.find('.xml')

            if index > 0:

                #print index, fname[:index]

                createCSVFile(fname[:index])

                print "Transform " + fname + " OK!"

if __name__ == '__main__':

    main()

    input("Game Over!")

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档