如何在 Python 中获取当前工作目录中的文件夹列表?
我只需要文件夹,不需要文件或子文件夹。
问问题
1811 次
2 回答
3
简单的列表理解:
[fn for fn in os.listdir(u'.') if os.path.isdir(fn)]
于 2013-02-11T09:38:03.577 回答
0
感谢@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
于 2013-02-11T09:35:35.593 回答