Python:如何检查文件夹中的文件夹? [英] Python: How to check folders within folders?

查看:113
本文介绍了Python:如何检查文件夹中的文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果标题不清楚,我要道歉.

First off, let me apologize if the title is unclear.

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

To simplify a task I do at work, I've started writing this script to automate the removal of files from a certain path.

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

My issue is that in its current state, this script does not check the contents of the folders within the folder provided by the path.

我不确定如何解决此问题,因为据我所知,应该正在检查那些文件?

I'm not sure how to fix this, because from what I can tell, it should be checking those files?

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()

推荐答案

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

Try using os.walk to traverse the directory tree, like this:

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)))

以下是文档(底部有一些用法示例):

Here are the docs (there are some usage examples towards the bottom): https://docs.python.org/3/library/os.html#os.walk

这篇关于Python:如何检查文件夹中的文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆