38. Filtering files

We are able to filter strings more concisely with fnmatch. Notice the second example uses a method, two for loops and an if statement?

38.1. Don’t do this

1files = ['one.txt', 'two.py', 'three.txt', 'four.py', 'five.scala', 'six.java', 'seven.py']
2
3py_files = filter(lambda f: f.endswith('.py'), files)
1import os
2
3def traverse(path):
4    for basepath, directories, files in os.walk(path):
5        for f in files:
6            if f.endswith('.ipynb'):
7                yield os.path.join(basepath, f)
8
9ipynb_files = traverse('./')

38.2. Do this

1import fnmatch
2
3files = ['one.txt', 'two.py', 'three.txt', 'four.py', 'five.scala', 'six.java', 'seven.py']
4
5fnmatch.filter(files, '*.py')
1import os
2
3ipynb_files = fnmatch.filter(
4    (f for basepath, directories, files in os.walk('./') for f in files),
5    '*.ipynb')
1import pathlib
2
3ipynb_files = pathlib.Path('./').glob('**/*.ipynb')