Parse all the xml files in a directory one by one using ElementTree
26,267
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)
Author by
Abhishek
HI i'm a Computer Science and Engineering student. I'm an ardent programmer and love building products.
Updated on October 06, 2020Comments
-
Abhishek over 3 years
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.
-
WinEunuuchs2Unix about 4 years@MartijnPieters As I discovered last night if you want 10 times the speed use:
import xml.etree.cElementTree as ET
and don't worry about changing any code. -
Martijn Pieters about 4 years@WinEunuuchs2Unix: better still: use lxml. Faster, and superior feature set.