[Stack Overflow上有很多帖子,它们解释了如何列出目录中的所有子目录。但是,所有这些答案都允许人们获得每个子目录的完整路径,而不仅仅是子目录的名称。
我有以下代码。问题是变量subDir[0]
输出每个子目录的完整路径,而不仅仅是子目录的名称:
import os
#Get directory where this script is located
currentDirectory = os.path.dirname(os.path.realpath(__file__))
#Traverse all sub-directories.
for subDir in os.walk(currentDirectory):
#I know none of my subdirectories will have their own subfolders
if len(subDir[1]) == 0:
print("Subdirectory name: " + subDir[0])
print("Files in subdirectory: " + str(subDir[2]))
如何获取每个子目录的名称?
例如,不要得到这个:
C:\ Users \ myusername \ Documents \ Programming \ Image-Database \ Curated \ Hype
我想要这样:
炒作
最后,我仍然需要知道每个子目录中的文件列表。
在'\'
上拆分子目录字符串就足够了。请注意,'\'
是转义字符,因此我们必须重复此操作以使用实际的斜杠。
import os
#Get directory where this script is located
currentDirectory = os.path.dirname(os.path.realpath(__file__))
#Traverse all sub-directories.
for subDir in os.walk(currentDirectory):
#I know none of my subdirectories will have their own subfolders
if len(subDir[1]) == 0:
print("Subdirectory name: " + subDir[0])
print("Files in subdirectory: " + str(subDir[2]))
print('Just the name of each subdirectory: {}'.format(subDir[0].split('\\')[-1]))
使用os.path.basename
for path, dirs, files in os.walk(currentDirectory):
#I know none of my subdirectories will have their own subfolders
if len(dirs) == 0:
print("Subdirectory name:", os.path.basename(path))
print("Files in subdirectory:", ', '.join(files))
os.path.isdir