DarkCeptor44
DarkCeptor44

Reputation: 314

os.path.isdir() returns false to an existing folder

I read this other post but none of the solutions there worked, say I have this folder structure:

main.py
src\
  s1\
    dummy.txt
  s2\
    dummy.txt

And this code:

import os

for filename in os.listdir('.'):
    isdir=os.path.isdir(filename)
    print('%s : %s'%(filename,isdir))

When I run it with . as the parameter of listdir() it works, it shows src : True and main.py : False which is right because there is a folder called src but when I try running it with src as parameter this is the output I get: s2 : False and s1 : False, it should return true because there are also two folders inside src which are called s1 and s2.

I can't really use escaped backslashes as the folder path is going to be provided by other functions so it's all dynamic, but I've tried dynamically replacing the backslashes to forward slashes and it also didn't work.

I created this Repl to show exactly what happens.

Upvotes: 0

Views: 1987

Answers (1)

abhilb
abhilb

Reputation: 5757

That is because it is checking if s1 is a directory under the current working directory.

>>> for x in os.listdir('src'):
...     print(f'Does {os.path.abspath(x)} exists? {os.path.exists(os.path.abspath(x))}')
...
Does d:\SO\tmp\s1 exists? False

So I would suggest to use scandir instead.

>>> with os.scandir('src') as it:
...     for entry in it:
...             print(f"{entry} is directory? {os.path.isdir(entry)}")
...
<DirEntry 's1'> is directory? True

It is even better if you use pathlib module for filesystem related stuff.

>>> from pathlib import Path
>>> entries = Path.cwd().glob("**/*")
>>> for entry in entries:
...     print(f"{entry} is a directory ? {entry.is_dir()}")
...
d:\SO\tmp\src is a directory ? True
d:\SO\tmp\src\s1 is a directory ? True

Upvotes: 2

Related Questions