Parse all the xml files in a directory one by one using ElementTree

不问归期 提交于 2019-12-08 15:01:15

问题


I'm parsing XML in python by ElementTree

import xml.etree.ElementTree as ET 
tree = ET.parse('try.xml')
root = tree.getroot()

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.


回答1:


Just create a loop over 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)


来源:https://stackoverflow.com/questions/15679467/parse-all-the-xml-files-in-a-directory-one-by-one-using-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!