glob
Look for a list of files on the file system with names matching a pattern
Pattern rules follow standard Unix path expansion rules
Wildcards
*, matches zero or more characters
?, matches any single character
[a-z] or [0-9], character range to match one of several characters
import glob
glob.glob('*') # get files under current directory
glob.glob('*.py') # get py files under current directory
glob.glob('p2/*') # get files under a subdirectory
glob.glob('p?.py') # wildcard character representing a single character
glob.glob('p[0-9].py') # character range
glob.glob(glob.escape('[')+'.py') # escape special characters
Recursive Search
import glob
glob.glob('**/*.py', recursive=True) # support for recursive globs using **
from pathlib import Path
[str(path) for path in Path('.').rglob('*.py')]
import os
files = []
for root, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith('.py'):
files.append(os.path.join(root, filename))
Relative Path Search
glob.glob('../*.py')
glob.glob('./*.py')
Absolute Path Search
glob.glob('/Users/lin/Documents/Skills/Python/*.py')
Reference