Why does the function .isdir() from the os module work properly on cwd but not on joined directories?

131 views Asked by At

I don't understand why my first for loop works as intended (prints all the folders from the cwd) but my second for loop (which should do the same but in an updated directory) doesn't.

If i print "stuff" and "stuff_t" they both correctly return the list of all the elements in the given directory. Here's the code (dirname is the name of a folder in the starting directory):

import os
import os.path

def es68(dirname):

cwd = os.getcwd()
stuff = os.listdir(cwd)

for i in stuff:
    if os.path.isdir(i) == True:
        print(i)

t = os.path.join(cwd, dirname)
stuff_t = os.listdir(t)

for i in stuff_t:
    if os.path.isdir(i) == True:
        print(i)
2

There are 2 answers

0
Mohammad Rifat Arefin On

stuff_t = os.listdir(t) returns only the relative paths. The reason it does not work in the second loop is because you are not in the cwd anymore. To make your code work, change the following loop:

t = os.path.join(cwd, dirname)
stuff_t = os.listdir(t)

for i in stuff_t:
    if os.path.isdir(os.path.join(t,i)) == True:
        print(i)
0
Matthias On

i contains only the pure name of the file or directory, not the full path. You have to add the path: if os.path.isdir(os.path.join(t, i)) == True:

But nowadays I would use the newer pathlib anyway.

import pathlib

dirname = 'mysubdir'

cwd = pathlib.Path.cwd()

for entry in cwd.iterdir():
    if entry.is_dir():
        print(entry)

t = cwd / dirname
for entry in t.iterdir():
    if entry.is_dir():
        print(entry)