Parse all the xml files in a directory one by one

2019-06-17 08:20发布

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.

1条回答
干净又极端
2楼-- · 2019-06-17 09:15

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)
查看更多
登录 后发表回答