Last modified: Feb 15, 2023 By Alexander Williams
Python Glob - How to Find Files in Python
In this tutorial, we'll learn how to find a file matching a specified pattern in python.
To do that, python provides us a built-function name's glog().
1. Finding a file on directory
In the following example, we'll find all files that end with .txt.
But first, let's see what we have in our directory.
glob.glob('/home/py/Desktop/glob/*')
the pattern "*" : find all files in the /home/py/Desktop/glob/
output:
# ['/home/py/Desktop/glob/image.jpg', '/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/image-1.jpg', '/home/py/Desktop/glob/test.txt', '/home/py/Desktop/glob/video.mp4', '/home/py/Desktop/glob/image-3.jpg', '/home/py/Desktop/glob/image-2.mp4']
Now, let's retrieve files that end with .txt.
glob.glob('/home/py/Desktop/glob/*.txt')
output:
#['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt']
2. Finding a file on multi directories
Example:
glob.glob('/home/py/Desktop/glob/**/*.txt', recursive=True)
“**”: will match any files and zero or more directories and subdirectorie.
output:
['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt', '/home/py/Desktop/glob/folder2/testfolder.txt']