Expanding filenames
In the everyday use of our system, we are used to providing paths, such as *.py
, to identify all the Python files, so it's not a surprise that our users expect to be able to do the same when they provide one or more files to our software.
Usually, wildcards are expanded by the shell itself, but suppose you are reading them from a configuration file or you want to write a tool that clears the .pyc
files (a cache of compiled Python bytecode) in your current project, then the Python standard library has what you need.
How to do it...
The steps for this recipe are:
pathlib
is able to perform many operations on the path you provided. One of them is resolving wildcards:
>>> list(pathlib.Path('.').glob('*.py'))
[PosixPath('conf.py')]
- It also supports resolving wildcards recursively:
>>> list(pathlib.Path('.').glob('**/*.py'))
[PosixPath('conf.py'), PosixPath('venv/bin/cmark.py'),
PosixPath('venv/bin/rst2html.py'), ...]