【问题标题】:Recursively go through all directories until you find a certain file in Python递归遍历所有目录,直到在 Python 中找到某个文件
【发布时间】:2017-02-14 05:36:02
【问题描述】:

在 Python 中递归遍历所有目录直到找到某个文件的最佳方法是什么? 我想查看我目录中的所有文件,看看我要查找的文件是否在该目录中。 如果找不到,我会转到父目录并重复该过程。我也想数 在找到文件之前我经过了多少个目录和文件。如果没有文件在 循环结束返回没有文件

startdir = "用户/..../file.txt"

findfile 是文件名。这是我当前的循环,但我想使用递归使其工作。

def walkfs(startdir, findfile):
    curdir = startdir
    dircnt = 0
    filecnt = 0
    for directory in startdir:
        for file in directory:
            curdir = file
            if os.path.join(file)==findfile:
                return (dircnt, filecnt, curdir)
            else:
                dircnt+=1
                filecnt+=1

【问题讨论】:

标签: python file recursion directory


【解决方案1】:

不要重新发明目录递归轮。只需使用os.walk() function,它会为您提供递归遍历目录的循环:

def walkfs(startdir, findfile):
    dircount = 0
    filecount = 0
    for root, dirs, files in os.walk(startdir):
        if findfile in files:
            return dircount, filecount + files.index(findfile), os.path.join(root, findfile)
        dircount += 1
        filecount += len(files)
    # nothing found, return None instead of a full path for the file
    return dircount, filecount, None

【讨论】:

  • 我想他说他只是想返回他找到的第一条路径
  • @JoranBeasley:是什么让你认为这不是那样的?
  • derr...对不起...我只是看到了计数的东西,就像一个白痴以为你在计数匹配:P
  • @JoranBeasley:我还想计算在找到文件之前我经过了多少目录和文件
【解决方案2】:
def findPath(startDir,targetFile):
    file_count = 0
    for i,(current_dir,dirs,files) in enumerate(os.walk(startDir)):
        file_count += len(files)
        if targetFile in files:
           return (i,file_count,os.path.join(current_dir,targetFile))
    return (i,file_count,None)

print findPath("C:\\Users\\UserName","some.txt")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2015-05-18
    • 2012-03-10
    • 2013-01-23
    • 2019-01-21
    • 2018-11-15
    • 2017-12-12
    相关资源
    最近更新 更多