How to find all .yml and .yaml files using a single glob pattern? Desired output:
>>> import os, glob
>>> os.listdir('.')
['f1.yaml', 'f2.yml', 'f0.txt']
>>> glob.glob(pat)
['f1.yaml', 'f2.yml']
Attempts that don't work:
>>> glob.glob("*.ya?ml")
[]
>>> glob.glob("*.y[a]ml")
['f1.yaml']
Current workaround is globbing twice, but I want to know if this is possible with a single pattern.
>>> glob.glob('*.yaml') + glob.glob('*.yml')
['f1.yaml', 'f2.yml']
Not looking for more workarounds, if this is not possible with a single pattern then I'd like to see an answer like "glob can not find .yaml
and .yml
files with a single pattern because of these reasons..."
Glob does not handle regular expression, but we can further refine its output. First, we would glob:
raw = glob("*.y*ml")
This will match *.yml, *.yaml; but also matches *.you-love-saml or *.yoml. The next step is to filter the raw list to our specifications:
result = [f for f in raw if f.endswith((".yml", ".yaml"))]