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

How to use wild card in filename that needs to be parsed using Element Tree

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

When I use a wild card for the code below it gives me an error but when I use the full filename it does not. How to use wildcards in the file name?

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()

I get the error below:

OSError: [Errno 22] Invalid argument: 'Data*.xml"

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

I fixed this issue by doing getting all files in the current directory and check if it starts with the string.

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)

There must be an easier way, I am not sure why ET.parse cannot handle wild cards.