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

Abhishek picture Abhishek · Mar 28, 2013 · Viewed 20.1k times · Source

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.

Answer

Martijn Pieters picture Martijn Pieters · Mar 28, 2013

Just create a loop over os.listdir():

import xml.etree.ElementTree as ET
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)