Python рекурсивно до 5 уровней для папок и файлов - PullRequest
0 голосов
/ 29 апреля 2020

Я ищу более элегантное решение проблемы, с которой я сталкиваюсь, пытаясь вернуться к нескольким уровням, чтобы вывести список каталогов и файлов.

os.walk(folder) выполняет под- и под-подуровни, но я нужно go как минимум до 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 () делает.

Спасибо

1 Ответ

0 голосов
/ 30 апреля 2020

Так что частью этого было моё недоразумение о том, как работает os.walk, я полагал, что вам нужно перебирать все каталоги с for d in dirs. однако, похоже, он делает это уже с for f in files

Я обошел это, позволив файлам делать свое дело, а затем заменив root на rootPath, который я изначально предоставил, так как я хотел только имена каталогов после этого вся строка пути.

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
...