Glob. This module provides a way to search through files—with an asterisk character, we can perform pattern matching on the file names in a directory. A leading directory can be provided as well.
While this functionality could be duplicated with more complex program logic, glob offers a pre-built module that can be used throughout many Python programs with no duplicated code.
Example. To begin, please run this program in a directory that contains some text (txt) files. And part of the program will only show results when run in a Windows operating system.
Part 1 We invoke glob.glob with a regular-expression-like pattern. This matches all files ending with the extension ".txt".
Part 2 We can use glob on a fully-formed path string containing a leading directory. Again, the star matches all possible values.
Part 3 With iglob() we get an iterator of the results. So we have to evaluate the result in a for-loop.
import glob
# Part 1: get all text files in current working directory.
result = glob.glob("*.txt")
print(result)
# Part 2: use glob with a complete raw string path.
result = glob.glob(r"C:\windows\*.exe")
print(result[0:3]) # Display first 3 results only.# Part 3: use iglob and iterate over the results.
for item in glob.iglob("*.txt"):
print("IGLOB:", item)['example.txt', 'example2.txt', 'hello.txt', 'words.txt']
['C:\\windows\\bfsvc.exe', 'C:\\windows\\explorer.exe', 'C:\\windows\\HelpPane.exe']
IGLOB: example.txt
IGLOB: example2.txt
IGLOB: hello.txt
IGLOB: words.txt
Summary. For pattern-matching on file names in Python programs, glob is effective and can be reused in many programs. It is powerful, but may incur CPU runtime costs.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.