如何将一个文件夹中的多个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
相关文章