Взлом на итерационный процесс os.walk()
Моя цель - хранить все файлы и каталоги в структурированном дереве данных, где каждый из них:
- каталог является узлом
- файл это лист
Мой код ниже работает нормально. Однако я делаю только один шаг за раз и прерываю / перезапускаю процесс обхода для каждого каталога. (увидеть step_in()
метод)
По-видимому, это можно считать "продвинутым", чтобы разбить сам процесс итерации и работать с ним. Поэтому мой вопрос: можно ли "взломать" процесс os.walk и получить то, что необходимо?
import os
import sys
import inspect
DEBUG = True
def report(*args,**kwargs):
global DEBUG
if DEBUG: print(*args,**kwargs)
class directory:
def __init__(self, path):
self.path = path
@property
def name(self):
return os.path.basename(self.path)
def __repr__(self):
ID = hex(id(self))
return "<directory \"{:}\" at {}>".format(self.name,ID)
def step_in(self):
"""Step into the dir and find all files/dirs.
Step into the directory path and search for:
- directories --> add string name to children (SEMI CHILD)
- and files --> add string name to leafs
"""
for p,d,f in os.walk(self.path):
self.children = d
report("--->kids found : {}".format(d))
self.leafs = f
report("--->leafs found: {}".format(f))
return p
class walker:
def __init__(self, root_path):
self.root = directory(root_path)
def walk(self, target=None):
"""Walk through all dirs and create tree.
Recursive process with root directory as initial directory.
"""
if not(target):
target = self.root
path = target.step_in()
for i in range(len(target.children)):
#get the next path
next_path = os.path.join(path,target.children[i])
report("\nnext is: {}".format(next_path))
#save dir by replacing the string child with an actual child
target.children[i] = directory(next_path)
#walk into that child
self.walk(target.children[i])
if __name__ == "__main__":
w = walker('/Users/xxx/test/xxx')
w.walk()