Warm tip: This article is reproduced from serverfault.com, please click

python-如何在需要使用元素树分析的文件名中使用通配符

(python - How to use wild card in filename that needs to be parsed using Element Tree)

发布于 2020-12-16 03:48:20

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

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”

Questioner
Ashim
Viewed
0
138k 2020-12-16 12:49:00

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

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不能处理通配符。