【发布时间】:2018-07-10 19:23:26
【问题描述】:
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
我想要这个:
炒作
最后,我还需要知道每个子目录中的文件列表。
【问题讨论】:
-
对于第一部分,将
str拆分为'\'并取最后一个元素。即sample_str.split('\')[-1]
标签: python python-3.x filesystems subdirectory python-os