【问题标题】:Search for files by name in multiple directories?在多个目录中按名称搜索文件?
【发布时间】:2013-04-24 17:01:26
【问题描述】:

好的,这是我的问题。我在工作时使用两个目录和目录中的所有子文件夹。我想编写一个程序,提示我输入文件名,在给出文件名后,它将搜索这两个目录以及这些目录中的所有子文件夹以查找具有匹配名称的任何文件。是否有捷径可寻。任何和所有的帮助将不胜感激。我想在 python 3 中执行此操作 (注意:这是我的第一个真正的项目,老实说,我不知道从哪里开始。)

【问题讨论】:

  • 您使用的是什么操作系统?在 *nix 上,您可以只使用 find(1)。
  • 我在 Windows 上。它是一台工作计算机,我没有安装 Linux 的选项,或者我会。

标签: python search windows-7 python-3.x directory


【解决方案1】:

这是一个带有递归辅助函数的函数,它返回文件夹中的所有文件(字典形式:{file_name: file_path, ...}

import os, os.path

def getFiles(path):
    '''Gets all of the files in a directory'''
    sub = os.listdir(path)
    paths = {}
    for p in sub:
        print p # just to see where the function has reached; it's optional
        pDir = os.path.join(path, p)
        if os.path.isdir(pDir): 
            paths.update(getAllFiles(pDir, paths))
        else:
            paths[p] = pDir
    return paths

def getAllFiles(mainPath, paths = {}):
    '''Helper function for getFiles(path)'''
    subPaths = os.listdir(mainPath)
    for path in subPaths:
        pathDir = pDir = os.path.join(mainPath, path)
        if os.path.isdir(pathDir):
            paths.update(getAllFiles(pathDir, paths))
        else:
            paths[path] = pathDir
    return paths

例如,如果您要查找 myfile.txt,则字典键值对之一将类似于 {'myfile.txt': 'C:\Users\Example\Path\myfile.txt', ...}

根据文件夹有多少文件,它可能会很慢。搜索我的sys.path(大概有10个文件夹,其中一个是Python\Lib,很大),大约需要9秒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-05-03
    • 2018-12-24
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多