Reputation: 841
I'm currently using os.walk
to list only the directories in a given folder. However, I need the absolute path for each directory listed.
My line of code:
folder_path = '/Users/username/Desktop/T'
array2 = next(os.walk(folder_path))[1]
print(array2)
It outputs:
['T1', 'T2', 'T3']
How can I get the absolute path of each directory?
The result I'm looking for would be:
['/Users/username/Desktop/T/T1', '/Users/username/Desktop/T/T2', '/Users/username/Desktop/T/T3']
Upvotes: 0
Views: 976
Reputation: 113978
for current,dirs,files in os.walk(...):
for folder in dirs:
print os.path.abspath(os.path.join(current,folder))
if you just want the directories in T
from os import listdir
from os.path import isdir,join as pjoin
root = "/Users/username/Desktop/T"
print [pjoin(root,p) for p in listdir(root) if isdir(pjoin(root,p))]
Upvotes: 2
Reputation: 841
I combined os.path.abspath
and os.path.join
:
folder_path = '/Users/username/Desktop/T'
array2 = next(os.walk(folder_path))[1]
array3 = []
print(array2)
# ['T1', 'T2', 'T3']
for local_folder in array2:
array3.append( os.path.abspath(os.path.join(folder_path, local_folder)))
print(array3)
# ['/Users/username/Desktop/T/T1', '/Users/username/Desktop/T/T2', '/Users/username/Desktop/T/T3']
Upvotes: 0