Zack
Zack

Reputation: 2208

Listing directories in a specific path in Python

The below command gives an empty [] when I try to set the path in the dirPath variable. However it works only when I run this in the python interpreter by changing to that directory specified by dirPath. What is the problem here? I want this line to give the correct output from any directory.

print [os.path.abspath(name) for name in os.listdir(dirPath) if os.path.isdir(name)]           

Upvotes: 0

Views: 77

Answers (3)

Zack
Zack

Reputation: 2208

I tried the below and it lists the name properly. Something wrong with the absolute path usage. It would be great if someone could figure out the issue with that. As of now I am going ahead with the directory names and concatenating to get the full absolute path!

>>> for name in os.listdir("/home/clonedir"):
...     print(name)
... 
directory1
directory2
>>> 

Upvotes: 0

PeterE
PeterE

Reputation: 5855

Unless your current working dir (cwd) equals dirPath your code will not work as expected.

os.listdir(dirPath) returns a list of folder names (NOT paths!).

os.path.abspath(name) basically returns "cwd\name"

What you want is os.path.abspath( os.path.join( dirPath, name ) ), i.e. "dirPath\name".

So to get a list of paths you need something like:

path_list =  [path for path in (os.path.abspath( os.path.join( dirPath, name ) ) for name in os.listdir(dirPath)) if os.path.isdir(path)]

(Be aware that I'm not quite sure if this will work with python 2.7, as I only have p3 to test it atm.)

Upvotes: 1

user 12321
user 12321

Reputation: 2906

Try this code:

[x[0] for x in os.walk(directory)]

alternatively you can use

os.listdir(path)

as well.

Upvotes: 0

Related Questions