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.
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)