Home
Python
glob Module Example
This page was last reviewed on Jul 10, 2024.
Dot Net Perls
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.
Sort, File Size
File
Path
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.
for
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 10, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.