Python:如何检查文件夹中的文件夹?

Sch*_*tat 5 python directory path python-3.x

首先,如果标题不清楚,请允许我道歉。

为了简化我在工作中执行的任务,我开始编写此脚本来自动从特定路径中删除文件。

我的问题是,在当前状态下,此脚本不会检查路径提供的文件夹内的文件夹内容。

我不知道如何解决这个问题,因为据我所知,它应该检查这些文件?

import os


def depdelete(path):
    for f in os.listdir(path):
        if f.endswith('.exe'):
            os.remove(os.path.join(path, f))
            print('Dep Files have been deleted.')
        else:
            print('No Dep Files Present.')


def DepInput():
    print('Hello, Welcome to DepDelete!')
    print('What is the path?')
    path = input()
    depdelete(path)


DepInput()
Run Code Online (Sandbox Code Playgroud)

chr*_*ris 6

尝试使用os.walk遍历目录树,如下所示:

def depdelete(path):
    for root, _, file_list in os.walk(path):
        print("In directory {}".format(root))
        for file_name in file_list:
            if file_name.endswith(".exe"):
                os.remove(os.path.join(root, file_name))
                print("Deleted {}".format(os.path.join(root, file_name)))
Run Code Online (Sandbox Code Playgroud)

以下是文档(底部有一些使用示例):https://docs.python.org/3/library/os.html#os.walk