Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python name 'os' is not defined even though it is explicitly imported

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.

like image 226
Qubit1028 Avatar asked Jan 02 '15 19:01

Qubit1028


People also ask

Why is os not defined in Python?

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!

How define operating system in Python?

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.


Video Answer


1 Answers

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).

like image 197
Mark Ransom Avatar answered Sep 22 '22 18:09

Mark Ransom