Reputation: 1837
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.
Upvotes: 18
Views: 35964
Reputation: 1
def read_xml_files(input_folder, output_folder):
for root, dirs, files in os.walk(input_folder):
for file in files:
if file.endswith(".xml"):
file_path = os.path.join(root, file)
dest_path = os.path.join(output_folder, file)
shutil.copy(file_path, dest_path)
print(f"Copied {file_path} to {dest_path}")
Upvotes: 0
Reputation: 1
import os
import xml.etree.ElementTree as ET
def parse_xml(xml_path):
tree = ET.parse(xml_path)
root = tree.getroot()
classname = root.find('.//testcase').get('classname')
time = float(root.get('time'))
return classname, time
def main():
data_folder = 'programming/assignment-1/data/'
xml_files = [f for f in os.listdir(data_folder) if f.endswith('.xml')]
Upvotes: 0
Reputation: 1124788
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)
Upvotes: 22