本文介绍了从文件夹中打开并解析多个XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

以下Python代码适用于一种XML.当我尝试打开并解析多个具有相似结构并保存在文件夹中的XML文件时,就会出现问题(第4行-> data = open('[0-9] .xml',"rb").我正在尝试使用正则表达式,但是我不确定这是否也适用于命名文档.

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 -> data = open('[0-9].xml',"rb"). I am trying regular expressions, but I am not sure if that works for naming documents too.

所有文档的名称为"11111.xml,22222.xml,33333.xml ..." ,依此类推.

The name of all document is "11111.xml, 22222.xml, 33333.xml ..." and so on.

import xml.etree.ElementTree as ET
import re

data = open ('[0-9].xml',"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"))

推荐答案

您可以使用 glob 模块.

import glob
import xml.etree.ElementTree as ET

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

for filename in filenames:

    with open(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"))

这篇关于从文件夹中打开并解析多个XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:35