如何在Python中列出顶级目录? [英] How to list only top level directories in Python?
问题描述
这意味着我不需要列出文件名,也不需要额外的子文件夹。
让我们看一个例子是否有帮助。在当前目录中,我们有:
>>> os.listdir(os.getcwd())
['cx_Oracle-doc','DLLs','Doc','include','Lib','libs','LICENSE.txt','mod_p
ython-wininst.log','NEWS.txt','pymssql-wininst.log','python.exe','pythonw.ex
e','README.txt','Removemod_python。 exe','Removepymssql.exe','Scripts','tcl',
'Tools','w9xpopen.exe']
但是,我不想列出文件名。我也不想要像\Lib\curses这样的子文件夹。基本上我想要的工作如下:
>>> ('。'):
...打印dirnames
...打破
...
['cx_Oracle-doc' ,'DLL','Doc','include','Lib','libs','Scripts','tcl','Tools']
但是,我想知道是否有一个简单的方法来实现相同的结果。我得到的印象是,使用os.walk只返回顶层是效率低下/太多。
os.path.isdir()(并使用os.path.join()来获取真实路径):
> >>如果os.path.isdir(os.path.join(thedir,name))]
['ctypes','distutils','encodings','lib- tk','config','idlelib','xml','bsddb','hotshot','logging','doc','test','compiler','curses','site-packages'电子邮件','sqlite3','lib-dynload','wsgiref','plat-linux2','plat-mac']
I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:
>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.
Filter the result using os.path.isdir() (and use os.path.join() to get the real path):
>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
这篇关于如何在Python中列出顶级目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!