天天看點

利用Python進行XML轉CSV

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

上一篇: 2020-04-01