Giovanni Montaruli
Giovanni Montaruli

Reputation: 1

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

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)

Upvotes: 0

Views: 160

Answers (2)

Matthias
Matthias

Reputation: 13222

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)

Upvotes: 0

Mohammad Rifat Arefin
Mohammad Rifat Arefin

Reputation: 427

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)

Upvotes: 0

Related Questions