Python 有没有一种在目录中递归的有效方法?

Python 有没有一种在目录中递归的有效方法?,python,file,Python,File,我想表演: 迭代文件夹的内容 如果内容是文件,请附加到列表 如果内容是文件夹,则转到1 如果文件夹名为“depth”或“ir”,则忽略 我正在使用python。你能帮忙吗?试试这个 import os basepath ="<path>" files=[] def loopover(path): contents = os.listdir(path) for c in contents: d = os.path.join(path,c)

我想表演:

  • 迭代文件夹的内容

  • 如果内容是文件,请附加到列表

  • 如果内容是文件夹,则转到1

  • 如果文件夹名为“depth”或“ir”,则忽略

  • 我正在使用python。你能帮忙吗?

    试试这个

    import os
    basepath ="<path>" 
    files=[]
    def loopover(path):
        contents = os.listdir(path)
        for c in contents:
            d = os.path.join(path,c)
            if os.path.isfile(d):
                files.append(c)
            if os.path.isdir(d):
                if (c=="depth" or c=="ir"):
                    continue
                else:
                    loopover(d)
    
    loopover(basepath)
    
    导入操作系统
    basepath=“”
    文件=[]
    def环路(路径):
    contents=os.listdir(路径)
    对于目录中的c:
    d=os.path.join(路径,c)
    如果os.path.isfile(d):
    文件。追加(c)
    如果os.path.isdir(d):
    如果(c==“深度”或c==“ir”):
    持续
    其他:
    环路(d)
    环路(基本路径)
    
    操作系统行走()将为您重现

    导入操作系统
    res=[]
    对于os.walk('/path/to/dir')中的(根、目录、文件):
    #root是指向dir的绝对路径,因此请检查最后一部分是depth还是ir
    如果root.split(“/”[-1]在[“深度”,“ir”]:
    持续
    其他:
    #文件是一个文件列表
    res.extend(文件)
    打印(res)
    
    最后做了如下事情:

    _files = []
    dir = "path/to/folder"
    for root, dirs, files in os.walk(dir, topdown=False):
        for name in files:
            files = os.path.join(root, name)
            if root.split("/")[-1] in ["depth", "ir"]:
                continue
            _files.append(files)
     print(_files)
    

    添加一些示例代码您似乎得到了逻辑,要检查路径是文件还是目录,请使用
    os.path.isfile()
    os.path.isdir()
    。要遍历文件夹,请选中此项