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.


the pattern "*" : find all files in the /home/py/Desktop/glob/


# ['/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.



#['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt']

2. Finding a file on multi directories


 glob.glob('/home/py/Desktop/glob/**/*.txt', recursive=True)

“**”: will match any files and zero or more directories and subdirectorie.


['/home/py/Desktop/glob/test2.txt', '/home/py/Desktop/glob/test.txt', '/home/py/Desktop/glob/folder2/testfolder.txt']

English today is not an art to be mastered it's just a tool to use to get a result