首页 > 解决方案 > 目录递归只深入一个目录

问题描述

我正在用 Python 编写一个脚本,以从编译内容中删除所有剩余的 .exe 文件:

import os

main_dir = '../RemoveExes'


def remove_all_in_dir(path):
    print(f'Currently in {path}. Listdir:', os.listdir(path))
    for current_name in os.listdir(path):
        if os.path.isdir(current_name):
            print(f'{path}/{current_name} is a directory. Entering')
            remove_all_in_dir(f'{path}/{current_name}')
        elif current_name.endswith('.exe'):
            print(f'Would remove: {current_name}')
        else:
            print(f'{current_name} is not an .exe or a directory. Omitting.')


remove_all_in_dir(main_dir)

../RemoveExes 是一个具有以下结构的目录:

 RemoveExes
 ├  bar
 │  ├  subdir
 │  │  ├ bulb.exe
 │  │  └ some_text.txt
 │  ├ doc.docs
 │  └ een.jpg
 ├  foo
 │  ├ exe.exe
 │  └ txt.txt
 ├ cleanup.py
 ├ prog.exe
 ├ script.py
 └ text.txt

该程序成功地“删除”了 exe.exe(1 个目录深)和 prog.exe(0 个目录深),但没有触及bulb.exe(2 个目录深)。这是为了限制 Python 中的递归,还是我做错了什么?

标签: pythonrecursion

解决方案


os.listdir仅返回文件名列表,不包含目录名,因此您应该将目录名与文件名连接起来以形成完整的路径名:

def remove_all_in_dir(path):
    print(f'Currently in {path}. Listdir:', os.listdir(path))
    for current_name in os.listdir(path):
        full_path = os.path.join(path, current_name)
        if os.path.isdir(full_path):
            print(f'{full_path} is a directory. Entering')
            remove_all_in_dir(f'{full_path}')
        elif current_name.endswith('.exe'):
            print(f'Would remove: {full_path}')
        else:
            print(f'{full_path} is not an .exe or a directory. Omitting.')

推荐阅读