Skip to content Skip to sidebar Skip to footer

Open And Parse Multiple Xml Files From A Folder

The Python code below works for one XML. The problem comes when I try to open and parse multiple XML files, which have a similar structure and are saved in the folder (line 4 ->

Solution 1:

You can use glob module.

import glob
import xml.etree.ElementTree as ET

filenames = glob.glob("[0-9].xml")  # change the pattern to match your casefor filename in filenames:

    withopen(filename, 'r', encoding="utf-8") as content:

        tree = ET.parse(content)

        lst_jugador = tree.findall('data_panel/players/player')

        for jugador in lst_jugador:

            print (jugador.find('name').text, jugador.get("id"))

Solution 2:

If all your the files in a directory need parsed, you could just use os.listdir()

from os import listdir
for file in listdir(<your directory>):
  #if you have to be more selective inside your directory#just add a conditional to skip herewithopen(file, "rb"):
    tree = ET.parse(data)
    lst_jugador = tree.findall('data_panel/players/player')
    for jugador in lst_jugador:
        print (jugador.find('name').text, jugador.get("id"))

Post a Comment for "Open And Parse Multiple Xml Files From A Folder"