如何将一个文件夹中的多个XML文件转换为CSV文件?

How convert multiple xml files in a folder in csv files with python?(如何将一个文件夹中的多个XML文件转换为CSV文件?)

本文介绍了如何将一个文件夹中的多个XML文件转换为CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1-我已经准备好了一个代码,然后将De XML文件转换为CSV。但实际上我需要做这个操作很多次,然后每次都需要在我的程序中更改XML文件的名称。我想做一个循环来读取文件夹位置中的每个‘.xml’文件,并对所有文件执行。这是我的原始代码
import xml.etree.ElementTree as ET
import csv

tree = ET.parse("Shot_30AA.xml")
root = tree.getroot()

Shot_30AA = open('Shot_30AA.csv', 'w', newline='')
csvwriter = csv.writer(Shot_30AA)
head = []

ShotCode = root.attrib['ShotCode']
csvwriter.writerow(['ShotCode', ShotCode])
head.append(ShotCode)

for member in root.getchildren():
  submembers = member.getchildren()
  keys = submembers[0].attrib.keys()
  csvwriter.writerow ("
")
  csvwriter.writerow(keys)
  for submember in submembers:
    row_data = [submember.attrib[k] for k in keys]
    csvwriter.writerow(row_data )
Shot_30AA.close()

我试图在我的文件夹中执行此操作,但添加了仅执行一次的休眠代码

path = 'C:/Users/Desktop/Program'
for filename in os.listdir(path):
   if not filename.endswith('.xml'): continue
     ShotFile = os.path.join(path, filename)
     tree = ET.parse(ShotFile)
     root = tree.getroot()

     filename = open( filename'.csv', 'w', newline='')
     csvwriter = csv.writer(filename)
     head = [] 

     ShotFile = open('ShotFile.csv', 'w', newline='')
     csvwriter = csv.writer(Shot_30AA)
     head = []

     ShotCode = root.attrib['ShotCode']
     csvwriter.writerow(['ShotCode', ShotCode])
     head.append(ShotCode)

     for member in root.getchildren():
       submembers = member.getchildren()
       keys = submembers[0].attrib.keys()
       csvwriter.writerow ("
")
       csvwriter.writerow(keys)
       for submember in submembers:
         row_data = [submember.attrib[k] for k in keys]
         csvwriter.writerow(row_data )
  ShotFile.close()

我希望一次运行即可获取CSV格式的所有文件。

推荐答案

以下是根据您的代码可以运行的

def make_csv(folderpath, xmlfilename):
    tree = ET.parse(os.path.join(folderpath, xmlfilename))
    root = tree.getroot()
    filename, _ = xmlfilename.rsplit('.', 1)
    Shot_30AA = open(filename+'.csv', 'w', newline='')
    csvwriter = csv.writer(Shot_30AA)
    head = []

    ShotCode = root.attrib['ShotCode']
    csvwriter.writerow(['ShotCode', ShotCode])
    head.append(ShotCode)

    for member in root.getchildren():
        submembers = member.getchildren()
        keys = submembers[0].attrib.keys()
        csvwriter.writerow("
")
        csvwriter.writerow(keys)
        for submember in submembers:
            row_data = [submember.attrib[k] for k in keys]
            csvwriter.writerow(row_data)
    Shot_30AA.close()

path = 'C:/Users/Desktop/Program'
for filename in os.listdir(path):
    if filename.endswith('.xml'):
        make_csv(path, filename)

编辑1:正如评论指出的那样,在处理文件时也应该查看with open() as clause

这篇关于如何将一个文件夹中的多个XML文件转换为CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何将一个文件夹中的多个XML文件转换为CSV文件?

基础教程推荐