NameError: name 'glob' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'glob' is not defined in Python #

The Python "NameError: name 'glob' is not defined" occurs when we use the glob module without importing it first. To solve the error, import the glob module before using it - import glob.

nameerror name requests is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'glob' is not defined print(glob.glob('./[0-9].*')) print(glob.glob('*.py'))

To solve the error, we have to import the glob module.

main.py
# 👇️ import the glob module first import glob print(glob.glob('./[0-9].*')) print(glob.glob('*.py'))

Even though the glob module is in the Python standard library, we still have to import it before using it.

Make sure you haven't used a capital letter g when importing glob because module names are case-sensitive.

Alternatively, you can make your code a little more concise by only importing the functions that you use in your code.

main.py
from glob import glob print(glob('./[0-9].*')) print(glob('*.py')) print(glob('**/*.txt', recursive=True))

The example shows how to only import the glob() function from the glob module.

Instead of accessing the functions on the module, e.g. glob.glob(), we now access them directly.

This should be your preferred approach because it makes your code easier to read.

For example, when we use an import such as import glob, it is much harder to see which functions from the glob module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which functions from the glob module are being used.

The glob module finds all the path names that match a specified pattern.

You will most often use the glob() function from the module.

The glob() function returns a list of path names that match the provided pathname argument.

If no files match the provided pathname, glob() returns an empty list.

If you set the recursive keyword argument to True, the pattern ** matches any files and zero or more directories, subdirectories and symbolic links to directories.

main.py
print(glob('**/*.txt', recursive=True))

For more details about the glob() function, visit the official docs.

Conclusion #

The Python "NameError: name 'glob' is not defined" occurs when we use the glob module without importing it first. To solve the error, import the glob module before using it - import glob.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.