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.
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.
glob.glob
with a regular-expression-like pattern. This matches all files ending with the extension ".txt".string
containing a leading directory. Again, the star matches all possible values.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
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.