Reputation: 2208
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
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
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
Reputation: 2906
Try this code:
[x[0] for x in os.walk(directory)]
alternatively you can use
os.listdir(path)
as well.
Upvotes: 0