列出目录并获取目录名称

chrissygormley:

我正在尝试获取代码以列出文件夹中的所有目录,将目录更改为该文件夹并获取当前文件夹的名称。我到目前为止的代码在下面,暂时无法正常工作。我似乎正在获取父文件夹名称。

import os

for directories in os.listdir(os.getcwd()): 
    dir = os.path.join('/home/user/workspace', directories)
    os.chdir(dir)
    current = os.path.dirname(dir)
    new = str(current).split("-")[0]
    print new

我的文件夹中还有其他文件,但我不想列出它们。我已经尝试了下面的代码,但我也没有使其正常工作。

for directories in os.path.isdir(os.listdir(os.getcwd())): 

谁能看到我要去哪里错了?

谢谢

它能正常工作,但似乎有点混乱。

import os
os.chdir('/home/user/workspace')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('/home/user/workspace', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("/")[4]
    print new
RichieHindle:

这将打印当前目录的所有子目录:

print [name for name in os.listdir(".") if os.path.isdir(name)]

我不确定您在做什么split("-"),但是也许这段代码可以帮助您找到解决方案?

如果需要目录的完整路径名,请使用abspath

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

请注意,这些代码片段将仅获取直接子目录。如果需要子目录等,则应使用walk其他建议的子目录

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章