Вы выполняете двойную работу с вызовом os.walk()
для подкаталогов, которые уже будут обрабатываться внешним циклом os.walk()
.
Все, что вам нужно проверить, это если migrations
является элементом втекущий root
путь к обрабатываемому каталогу:
def delete_py(path, subfolder):
for root, dirs, files in os.walk(path):
if subfolder in root.split(os.sep):
# has subfolder as a directory name in the path, delete .py files here
for file in files:
if file == '__init__.py':
continue
if file.endswith(('.py', '.pyc')):
os.unlink(os.path.join(root, file))
Вы также можете просто использовать рекурсивный шаблон glob с модулем glob
:
from itertools import chain
def delete_py(path, subfolder):
pyfiles = glob.iglob(f'**/{subfolder}/**/*.py', recursive=True)
pycfiles = glob.iglob(f'**/{subfolder}/**/*.pyc', recursive=True)
for filename in chain(pyfiles, pycfiles):
if os.path.basename(filename) == '__init__.py':
continue
os.unlink(filename)