首页 > 解决方案 > 如何在需要使用元素树解析的文件名中使用通配符

问题描述

当我对下面的代码使用通配符时,它会给我一个错误,但是当我使用完整的文件名时它不会。如何在文件名中使用通配符?

import xml.etree.ElementTree as ET

filename = sys.argv[2]

#file name is 'Data*.xml' as in the future it will change every month so need to use a wild card
tree = ET.parse(filename)
root = tree.getroot()

我收到以下错误:

OSError: [Errno 22] 无效参数:'Data*.xml"

标签: pythonxmlwildcardelementtree

解决方案


我通过获取当前目录中的所有文件并检查它是否以字符串开头来解决此问题。

files = [f for f in os.listdir('.') if os.path.isfile(f)]

for f in files:
    if f.startswith(sys.argv[2]):
        filename = f

tree = ET.parse(filename)

必须有一个更简单的方法,我不确定为什么ET.parse不能处理通配符。


推荐阅读