我正在尝试遍历顶级目录的子目录。 对于每个子目录,我想走进它的子目录,然后向下走进子目录的文件。
我看过有关os.walk的帖子,但是在花了几个早上的火车游玩之后,我无法想出解决方案。
我已经检查了os.walk的python文档,它没有帮助我。
为了澄清,这里是目录结构:
topdir
-> dirLesson1
-> dirLanguageA
-> file1
-> file2
-> dirLanguageB
-> file1
-> file2
-> dirLesson2
-> dirLanguageA
-> file1
-> file2
-> dirLanguageB
-> file1
-> file2
这是伪代码:
for dirLesson in topdir
# do something with dirLesson
for dirLanguage in dirLesson
# do something with dirLanguage
for file in dirLanguage
#do something with file
我是Python的新手,所以任何帮助都会受到赞赏。
答案 0 :(得分:0)
import os
def getSubDirs(dir):
return [os.path.join(dir,name) for name in os.listdir(dir)
if os.path.isdir(os.path.join(dir, name))]
def getSubFiles(dir):
return [os.path.join(dir,name) for name in os.listdir(dir)
if os.path.isfile(os.path.join(dir, name))]
indir = "/topdir"
subDirArr = []
subSubDirArr = []
subSubFileArr = []
subDirArr.extend(getSubDirs(indir))
for dir in subDirArr:
subSubDirArr.extend(getSubDirs(dir))
for dir in subSubDirArr:
subSubFileArr.extend(getSubFiles(dir))
print "Here i am doing operation on level1 dirs"
for dir in subDirArr:
print os.path.basename(dir)
print "Here i am doing operation on level2 dirs"
for dir in subSubDirArr:
print os.path.basename(dir)
print "Here i am doing operation on level3 files"
for file in subSubFileArr:
print os.path.basename(file)