码迷,mamicode.com
首页 > 编程语言 > 详细

利用Python进行XML转CSV

时间:2014-11-27 12:59:02      阅读:388      评论:0      收藏:0      [点我收藏+]

标签:python csv xml

#!/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!")


利用Python进行XML转CSV

标签:python csv xml

原文地址:http://tom008.blog.51cto.com/8612366/1583083

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!