[英]Listing directories in a specific path in Python
当我尝试在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。)
试试这个代码:
[x[0] for x in os.walk(directory)]
或者,您可以使用
os.listdir(path)
也一样
我在下面尝试过,它正确列出了名称。 绝对路径使用有问题。 如果有人能解决这个问题,那就太好了。 到目前为止,我将继续使用目录名称并进行连接以获取完整的绝对路径!
>>> for name in os.listdir("/home/clonedir"):
... print(name)
...
directory1
directory2
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.