kwotsin
kwotsin

Reputation: 2923

Python: os.path.isdir behaving strangely if the directory name has been changed to an equivalent one?

I am seeing a very strange behavior coming from these two commands:

k = [name for name in os.listdir('/home/kwotsin/Datasets/flowers/') if os.path.isdir(name)]

versus the following command when I run it in a terminal on the path above:

k = [name for name in os.listdir('.') if os.path.isdir(name)]

When I run this to check:

k = [name for name in os.listdir('/home/kwotsin/Datasets/flowers/')]
for name in k:
    print os.path.isdir(name)

I get False instead, although k actually has a subdirectory listed in it!

The first one returns me nothing while the second one returns me a list of subdirectories. Why would this happen?

Upvotes: 0

Views: 281

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46921

this is a problem because name (coming from os.listdir) will only contain the last part of the path and therefore be a relative path. os.isdir('testdir') will only look for 'testdir' in your current working directory (os.getcwd() will tell you which one that is; that is also what is referenced by '.').

you could fix that with something like

my_dir = '/home/kwotsin/Datasets/flowers/'
...
if os.isdir(os.path.join(my_dir, name)):
    ...

because now os.path.join(my_dir, name) is the absolute path of the directory/file called name in my_dir and it will be found independently of your working directory.

just in case: pathlib is a nice built-in module for path handling...

Upvotes: 4

Related Questions