Python Traverse Files in a Directory Using glob Library: A Beginner Guide – Python Tutorial

By | April 11, 2020

There are some way to traverse files in a directory using python. We can use os.scandir() function to do it. Here is an example:

Python Traverse Files in a Directory for Beginners – Python Tutorial

However, python glob library also can do it. In this tutorial, we will use some examples to show python beginners how to traverse.


We can use regular expression to match file path to traverse files in python glob.

* match all characters
? match only one character
*.* match [hello.txt ,site.xls, x4s.doc]
?.* match [1.docx,]
?.gif match [1.gif, 3.gif, a.gif]

Import glob library

We should import this library to start to traverse files.

import glob

In this example, we will travers all python script file in a directory.

Traverse all files in a directory

We will traverse all files in a directroy and its subdirectories. Here is an example.

files = glob.glob('E:\\workspace-nlp\\Example\\**\\*.py', recursive=True)

Run this code, you will get all python files in E:\\workspace-nlp\\Example and its subdirectories.

The result is:

<class 'list'>
['E:\\workspace-nlp\\Example\\','E:\\workspace-nlp\\Example\\package_1\\', 'E:\\workspace-nlp\\Example\\package_1\\', 'E:\\workspace-nlp\\Example\\package_1\\', 'E:\\workspace-nlp\\Example\\package_2\\', 'E:\\workspace-nlp\\Example\\package_2\\pk\\']

If you only want to get python files in E:\\workspace-nlp\\Example and they are not in its subdirectories, you can do like this:

files = glob.glob('E:\\workspace-nlp\\Example\\*.py')

The result will be:

<class 'list'>

Leave a Reply

Your email address will not be published. Required fields are marked *