【发布时间】:2013-02-11 09:32:06
【问题描述】:
如何在 Python 中获取当前工作目录中的文件夹列表?
我只需要文件夹,不需要文件或子文件夹。
【问题讨论】:
如何在 Python 中获取当前工作目录中的文件夹列表?
我只需要文件夹,不需要文件或子文件夹。
【问题讨论】:
简单的列表理解:
[fn for fn in os.listdir(u'.') if os.path.isdir(fn)]
【讨论】:
感谢@ATOzTOA
您可以像这里一样使用os.listdir 和os.path.isfile:
import os
path = 'whatever your path is'
for item in os.listdir(path):
if not os.path.isfile(os.path.join(path, item)):
print "Folder: ",item
else:
print "File: ",item
现在您知道什么是文件夹和什么是文件了。
由于您不需要文件,您可以简单地将文件夹(路径或名称)存储在列表中
为此,请执行以下操作:
import os
path = 'whatever your path is'
folders = [] # list that will contain folders (path+name)
for item in os.listdir(path):
if not os.path.isfile(os.path.join(path, item)):
folders.append(os.path.join(path, item)) # os.path.join(path, item) is your folder path
【讨论】: