首页 > 解决方案 > 目录和文件的 Python 递归到 5 个级别

问题描述

我正在寻找一个更优雅的解决方案来解决我在尝试递归到多个级别以列出目录和文件时遇到的问题。

os.walk(folder)做子和子子级别,但我至少需要深入5。

我想出了以下遍历多个目录的方法,但是,有没有更好或更优雅的方法我错过了?

rootPath = '/path/to/my/folder/test'

print '###### using os.walk ######'
for root, dirs, files in os.walk(rootPath):
    print 'directory - ' + " ".join(dirs)
    for d in dirs:
        for f in files:
            if not f.startswith('.'):
                print 'directory - ' + d + '  file - ' + f


print '\n\n\n###### using isdir ######'
for f in os.listdir(rootPath):
    print '-' + f
    if os.path.isdir(os.path.join(rootPath,f)):
        for fo in os.listdir(os.path.join(rootPath,f)):
            print '--' + fo
            if os.path.isdir(os.path.join(rootPath,f,fo)):
                for fol in os.listdir(os.path.join(rootPath,f,fo)):
                    print '---' + fol
                    if os.path.isdir(os.path.join(rootPath,f,fo,fol)):
                        for fold in os.listdir(os.path.join(rootPath,f,fo,fol)):
                            print '----' + fold
                            if os.path.isdir(os.path.join(rootPath,f,fo,fol,fold)):
                                for folde in os.listdir(os.path.join(rootPath,f,fo,fol,fold)):
                                    print '-----' + folde
                                    if os.path.isdir(os.path.join(rootPath,f,fo,fol,fold,folde)):
                                        for folder in os.listdir(os.path.join(rootPath,f,fo,fol,fold,folde)):
                                            print '------' + folder

输出:

###### using os.walk ######
directory - first
directory - second
directory - third
directory - fourth
directory - fourth  file - in_third.txt
directory - fifth
directory - fifth  file - in_fourth.txt
directory - 


###### using isdir ######
-.DS_Store
-first
---.DS_Store
---second
-----.DS_Store
-----third
------.DS_Store
------fourth
-------.DS_Store
-------in_fourth.txt
-------fifth
---------.DS_Store
---------in_fifth.txt
------in_third.txt

似乎 os.walk 没有进入“第五”文件夹以查看 in_fifth.txt,但是 isidr() 解决方案可以。

谢谢

标签: python-2.7os.walk

解决方案


所以部分原因是我对 os.walk 工作原理的误解,我相信你需要用for d in dirs. 但是,它似乎已经做到了for f in files

我通过让文件做它的事情来解决这个问题,然后用我最初提供的 rootPath 替换 root,因为我只想要整个路径字符串之后的目录名称。

rootPath = '/path/to/my/folder/test'
for root, dirs, files in os.walk(rootPath):
    for f in files:
        if not f.startswith('.'):
            print 'file - ' + os.path.join(os.path.join(root.replace(rootPath,''), f))

输出:

file - /test2/first/foobar/files1.txt
file - /test2/first/foo.txt
file - /extra/test/bar.bin

推荐阅读