I have a module called imtools.py
that contains the following function:
import os
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
When I attempt to call the function get_imlist
from the console using import imtools
and imtools.get_imlist(path)
, I receive the following error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\...\PycharmProjects\first\imtools.py", line 5, in get_imlist
NameError: name 'os' is not defined
I'm new at Python and I must be missing something simple here, but cannot figure this out. If I define the function at the console it works fine. The specific history of this module script is as follows: initially it was written without the import os
statement, then after seeing the error above the import os
statement was added to the script and it was re-saved. The same console session was used to run the script before and after saving.
The Python "NameError: name 'os' is not defined" occurs when we use the os module without importing it first. To solve the error, import the os module before using it - import os . Here is an example of how the error occurs. Copied!
The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, etc. You first need to import the os module to interact with the underlying operating system.
Based on small hints, I'm going to guess that your code didn't originally have the import os
line in it but you corrected this in the source and re-imported the file.
The problem is that Python caches modules. If you import
more than once, each time you get back the same module - it isn't re-read. The mistake you had when you did the first import will persist.
To re-import the imtools.py
file after editing, you must use reload(imtools)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With