[Solved] Python name ‘os’ is not defined even though it is explicitly imported

I have a module called 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 "", 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.

Solution #1:

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 file after editing, you must use reload(imtools).

Respondent: Qubit1028

Solution #2:

Same problem is with me I am also trying to follow the book of Programming Computer Vision with Python by Jan Erik Solem” []. I tried to explore on internet to see the problem but I did not find any valuable solution but I have solved this problem by my own effort.

First you just need to place the ‘’ into the parent folder of where your Python is installed like C:Python so place the file into that destination and type the following command:

from PIL import Image
from numpy import *
from imtools import *

Instead of typing the code with imtools.get_imlist() you just to remove the imtools from the code like:


This may solve your problem as I had found my solution by the same technique I used.

Respondent: Mark Ransom

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy