列出目录并获取目录的名称 [英] List Directories and get the name of the Directory
问题描述
我正在尝试获取代码列出文件夹中的所有目录,将目录更改为该文件夹,并获取当前文件夹的名称。到目前为止,我的代码是下面的代码,并且在一分钟之内不起作用。我似乎正在获取父文件夹名称。
I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
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
我还有文件夹中的其他文件,但我不想列出它们。我已经尝试了以下代码,但是我还没有工作。
I also have other files in the folder but I do not want to list them. I have tried the below code but I haven't got it working yet either.
for directories in os.path.isdir(os.listdir(os.getcwd())):
任何人都可以看到我错了什么?
Can anyone see where I am going wrong?
谢谢
得到它的工作,但似乎有点儿。
Got it working but it seems a bit round about.
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
推荐答案
这将打印当前目录的所有子目录:
This will print all the subdirectories of the current directory:
print [name for name in os.listdir(".") if os.path.isdir(name)]
我不知道你在做什么与 split( - )
,但是这个代码可能会帮助您找到解决方案?
I'm not sure what you're doing with split("-")
, but perhaps this code will help you find a solution?
如果您想要目录的完整路径名,请使用 abspath
:
If you want the full pathnames of the directories, use abspath
:
print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
请注意,这些代码段只会获得直接的子目录。如果你想要子子目录等等,你应该像其他人一样建议使用 walk
。
Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk
as others have suggested.
这篇关于列出目录并获取目录的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!