使用ElementTree逐一解析目录中的所有xml文件 [英] Parse all the xml files in a directory one by one using ElementTree
本文介绍了使用ElementTree逐一解析目录中的所有xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过ElementTree解析python中的XML
I'm parsing XML in python by ElementTree
import xml.etree.ElementTree as ET
tree = ET.parse('try.xml')
root = tree.getroot()
我希望解析给定目录中的所有"xml"文件.用户应该只输入目录名称,我应该能够遍历目录中的所有文件并逐一解析它们.有人可以告诉我方法.我正在使用Linux.
I wish to parse all the 'xml' files in a given directory. The user should enter only the directory name and I should be able to loop through all the files in directory and parse them one by one. Can someone tell me the approach. I'm using Linux.
推荐答案
只需在os.listdir()
上创建循环:
import os
path = '/path/to/directory'
for filename in os.listdir(path):
if not filename.endswith('.xml'): continue
fullname = os.path.join(path, filename)
tree = ET.parse(fullname)
这篇关于使用ElementTree逐一解析目录中的所有xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文