0

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)] 

3 Answers 3

1

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

Okay. Let me try this.
Yes...This works ..Thanks! So that was the default behaviour of absolute path .
abspath converts any relative path (a folder name is a relative path) into an absolute path by combining it with cwd (also it normalizes it by resolving things like "..").
0

Try this code:

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

alternatively you can use

os.listdir(path) 

as well.

3 Comments

I think walk would do recursive listing of directories which I want to avoid
Also it has the same problem as the OP
editing the 'dirnames' list will stop os.walk() from recursing into there.
0

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 >>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.