NameError: name 'xlrd' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

nameerror name xlrd is not defined

Open your terminal in your project's root directory and install the xlrd module.

shell
# 👇️ in a virtual environment or using Python 2 pip install xlrd # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install xlrd # 👇️ if you get permissions error sudo pip3 install xlrd # 👇️ if you don't have pip in your PATH environment variable python -m pip install xlrd # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install xlrd # 👇️ for Anaconda conda install -c anaconda xlrd

After you install the xlrd module, make sure to import it before using it.

main.py
# 👇️ import xlrd module first import xlrd book = xlrd.open_workbook("myfile.xls") print("The number of worksheets is {0}".format(book.nsheets))

An alternative to importing the entire xlrd module is to import only the functions that your code uses.

main.py
from xlrd import open_workbook book = open_workbook("myfile.xls") print("The number of worksheets is {0}".format(book.nsheets))

The example shows how to import the open_workbook function from the xlrd module.

Instead of accessing the members on the module, e.g. xlrd.open_workbook, 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 xlrd, it is much harder to see which functions from the xlrd module are being used in the file.

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

Conclusion #

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

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.