Python's os.path.isdir() quirk

September 04, 2017

Context

Python’s os.path.isdir() is a much used function, but today, I wasn’t getting the expected results.
My directory looks like this:

|_root/
    |_colors/
        |_blue/
        |   |_blue1.jpg
        |   |_blue2.jpg
        |_red
            |_red1.jpg
            |_red2.jpg

When I ran the code snippet below, I was getting all nothing. os.path.isdir() was return ‘False’ on all of the color folders:

colors_dir = os.path.join(os.path.abspath("root"), "colors")

for i in os.listdir(colors_dir):
    if os.path.isdir(i):
        print i

Solution

You need the entire path to the entry for os.path.isdir() to detect file|folder correctly. So:

colors_dir = os.path.join(os.path.abspath("root"), "colors")

for i in os.listdir(colors_dir):
    if os.path.isdir(os.path.join(colors_dir, i)):
        print i