PythonStudy——递归 Recursive

递归删除的思路

def delete_dir(folder):
    for path in os.listdir(folder):
        # 如果path是文件夹 delete_dir(path)
        # 如果是文件os.remove(path)
        pass
    # for走完了代表folder内部删空了,可以删folder

递归遍历打印目标路径中所有的txt文件

def print_txt(folder):
    if not os.path.exists(folder) or os.path.isfile(folder):
        return
    for path in os.listdir(folder):
        file_path = os.path.join(folder, path)
        if os.path.isfile(file_path) and file_path.endswith('.txt'):
            print(path)
        elif os.path.isdir(file_path):
            print_txt(file_path)  # 递归


target_path = os.path.join(BASE_DIR, 'part6', 'target')
print_txt(target_path)
原文地址:https://www.cnblogs.com/tingguoguoyo/p/10834403.html