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

I am parsing XML in python using ElementTree

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

I want to parse all the "xml" files in this directory. The user should specify only the directory name, and I should be able to iterate over all the files in the directory and analyze them one by one. Can anyone tell me this approach. I am using Linux.

+4
source share
1 answer

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) 
+8
source

All Articles