Is it possible to glob for *.yaml and *.yml files in one pattern?

481 views Asked by At

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..."

3

There are 3 answers

0
Hai Vu On BEST ANSWER

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"))]
2
Barmar On

Use glob.glob('*.y*ml'). This will only fail in the unlikely case that you have some other extensions that begin with y and end with ml (e.g. foo.yabcml).

2
Simon1 On

You can build a list containing all .yml and .yaml files like this:

files = []
for ext in ('*.yml', '*.yaml'):
    files.extend(glob.glob(ext))

If you want to recursively search all sub directories instead of just the current directory, you can use glob.glob(ext, recursive=True) instead.