1-我准备好将代码转换为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 ("\n")
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 ("\n")
csvwriter.writerow(keys)
for submember in submembers:
row_data = [submember.attrib[k] for k in keys]
csvwriter.writerow(row_data )
ShotFile.close()
我希望一次运行即可获得csv格式的所有文件。
答案 0 :(得分:0)
根据您的代码,这可能会起作用
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("\n")
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