我目前正在使用os.walk
仅列出给定文件夹中的目录。但是,我需要列出的每个目录的绝对路径。
我的代码行:
folder_path = '/Users/username/Desktop/T'
array2 = next(os.walk(folder_path))[1]
print(array2)
输出:
['T1', 'T2', 'T3']
如何获取每个目录的绝对路径?
我正在寻找的结果将是:
['/Users/username/Desktop/T/T1', '/Users/username/Desktop/T/T2', '/Users/username/Desktop/T/T3']
答案 0 :(得分:2)
for current,dirs,files in os.walk(...):
for folder in dirs:
print os.path.abspath(os.path.join(current,folder))
如果您只想要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))]
答案 1 :(得分:0)
试试这个:
for o in array2:
print os.path.abspath(o)
答案 2 :(得分:0)
我合并了os.path.abspath
和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']