当我尝试在dirPath变量中设置路径时,以下命令会提供一个空的[]。但是,仅当我通过更改到dirPath指定的目录在python解释器中运行此命令时,此命令才起作用。这里有什么问题?我希望此行提供任何目录的正确输出。
print [os.path.abspath(name) for name in os.listdir(dirPath) if os.path.isdir(name)]
除非您当前的工作目录(cwd)等于dirPath
您的代码,否则它将无法按预期工作。
os.listdir(dirPath)
返回文件夹名称列表(无路径!)。
os.path.abspath(name)
基本返回 "cwd\name"
你想要的是os.path.abspath( os.path.join( dirPath, name ) )
,即"dirPath\name"
。
因此,要获取路径列表,您需要类似以下内容:
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)]
(请注意,我不太确定这是否适用于python 2.7,因为我只有p3可以测试atm。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句