【问题标题】:Python: How to check folders within folders? [duplicate]Python:如何检查文件夹中的文件夹? [复制]
【发布时间】:2019-01-24 13:05:20
【问题描述】:

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

为了简化我在工作中所做的任务,我已经开始编写这个脚本来自动从某个路径中删除文件。

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

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

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

标签: python python-3.x path directory


【解决方案1】:

您正在寻找os.walk()。在你的情况下,它可以像这样工作:

import os

def dep_delete(path):
    for path, dirs, files in os.walk(path):
       for f in files: 
           if f.endswith('.exe'):
               os.remove(os.path.join(path, f))
    print('Dep files have been deleted.')

def dep_input():
    print('Hello, Welcome to dep_delete!')
    print('What is the path?')
    path = input()
    dep_delete(path)


dep_input()

另见:List directory tree structure in python?

【讨论】:

    【解决方案2】:

    看看os.walk()

    此函数将为您遍历子目录。循环将如下所示。

    for subdir, dirs, files in os.walk(path):
        for f in files:   
          if f.endswith('.exe'):
              fullFile = os.path.join(subdir, f)
              os.remove(fullFile)
              print (fullFile + " was deleted")
    

    【讨论】:

      【解决方案3】:

      目前,您的代码只会遍历所提供文件夹中的所有文件和文件夹,并检查每个文件和文件夹的名称。为了同时检查路径中文件夹的内容,您必须使代码递归。

      您可以使用 os.walk 遍历 path 中的目录树,然后检查其内容。

      您可以在Recursive sub folder search and return files in a list python 找到更详细的代码示例答案。

      【讨论】:

        【解决方案4】:

        尝试使用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)))
        

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

        【讨论】:

        • 更好地使用fnmatch.fnmatch(file_name,"*.exe"),以便处理小写/大写的.EXE/.exe 扩展
        猜你喜欢
        • 2012-05-10
        • 2022-01-06
        • 2012-09-16
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        • 2012-07-12
        • 2011-10-05
        • 2011-04-20
        相关资源
        最近更新 更多