Python:如何在仅有文件名时进行全系统搜索文件

10 投票
3 回答
14632 浏览
提问于 2025-04-16 12:44

我刚开始学习Python(用的是2.6版本),现在想在整个系统中搜索一个文件,只知道文件名,然后返回这个文件在Windows上的绝对路径。我查了一些资料,找到了像scriptutil.py这样的模块,也看了一下os模块,但没找到适合我需求的东西(或者我可能没有完全理解这些内容,导致无法应用到我的需求上,所以没有提供任何代码)。希望能得到一些帮助。

谢谢。

3 个回答

0

这样做可以吗?

import os
import sys
import magic
import time
import fnmatch

class FileInfo(object):

    def __init__(self, filepath):
        self.depth = filepath.strip('/').count('/')
        self.is_file = os.path.isfile(filepath)
        self.is_dir = os.path.isdir(filepath)
        self.is_link = os.path.islink(filepath)
        self.size = os.path.getsize(filepath)
        self.meta = magic.from_file(filepath).lower()
        self.mime = magic.from_file(filepath, mime=True)
        self.filepath = filepath


    def match(self, exp):
        return fnmatch.fnmatch(self.filepath, exp)

    def readfile(self):
        if self.is_file:
            with open(self.filepath, 'r') as _file:
                return _file.read()

    def __str__(self):
        return str(self.__dict__)



def get_files(root):

    for root, dirs, files in os.walk(root):

        for directory in dirs:
            for filename in directory:
                filename = os.path.join(root, filename)
                if os.path.isfile(filename) or os.path.isdir(filename):
                    yield FileInfo(filename)

        for filename in files:
            filename = os.path.join(root, filename)
            if os.path.isfile(filename) or os.path.isdir(filename):            
                yield FileInfo(filename)


for this in get_files('/home/ricky/Code/Python'):
    if this.match('*.py'):
        print this.filepath
4

你可以从目录开始,逐层遍历整个文件夹结构,查看每一层是否有你要找的文件。当然,如果你想搜索整个系统,就需要对每个驱动器都执行这个操作。

os.path.walk(rootdir,f,arg)

这里有一个关于类似问题的好答案,可以查看这里,还有另一个答案在这里

17

os.walk() 函数是一种实现这个功能的方法。

import os
from os.path import join

lookfor = "python.exe"
for root, dirs, files in os.walk('C:\\'):
    print "searching", root
    if lookfor in files:
        print "found: %s" % join(root, lookfor)
        break

撰写回答