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"
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.
ElementTree.parse()
, much like Python'sopen()
function, only accepts a literal. file name. What would it mean for it to open many files at the same time? You can easily loop over all matches withglob.glob()
or the more modernpathlib.Path.glob()
or like you do here withos.listdir()
and open each one separately, or pick out and open the ones you want.