![]() |
VOOZH | about |
If we are working with Python and encounter an error that says "NameError: name 'os' is not defined", then we need not worry, it is a very common issue, and fixing this error is very simple. This error usually occurs when we try to use the os module without importing it first. In this article, we will learn what this error means, and how we can fix it.
When we see the error message "NameError: name 'os' is not defined", it means that Python doesn't recognize OS module because it hasn't been imported into our script. Before using certain functions or modules, we need to tell the program where to find them by using an import statement.
We need to import the os module at the beginning of your script to fix this error. Below is how we can do it:
Add the Import Statement
At the very top of our Python file, we need to add import os:
import osExample:
After importing the "os" module we can use its functions and methods without any issues.
Output:
Current Directory: /home/guest/sandbox
Files and Directories: ['input.txt', 'driver', 'Solution.py']
In this example, we used os.getcwd() to get the current working directory and os.listdir() to list all files and directories in that directory.
Sometimes when we forget to include the import os line, especially when we are copying code snippets from different places or if we are new to Python. Without this import, Python has no idea what os is, which leads to the NameError.
Example
Let's write a incorrect code to encounter this error :
Incorrect Code:
Output:
NameError: name 'os' is not defined
Fixed Code:
Output:
Current Directory: /home/guest/sandboxThe "NameError: name 'os' is not defined" error in Python is very easy to fix once we understand what it means. Just remember to import the os module at the start of our script, and our code will work fine and we will not get this error.