开发者

Python: How to do a system wide search for a file when just the filename (not path) is available

开发者 https://www.devze.com 2023-02-14 06:18 出处:网络
I\'m still new to Python (using 2.6) and I am trying to do a system wide search for a file when just the filename is available and return the absolute path on windows. I\'ve searched and found some mo

I'm still new to Python (using 2.6) and I am trying to do a system wide search for a file when just the filename is available and return the absolute path on windows. I've searched and found some modules like scriptutil.py and looke开发者_运维百科d through the os module but haven't found anything that suits my needs (or I may not have understood everything correctly to apply it to what I need and thus have not included any code). I would appreciate any help.

Thanks.


The os.walk() function is one way of doing it.

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


You could start at the root directory and recursively walk the directory structure looking at each level for the file. Of course if you want to search your entire system you will need to call this for each drive.

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

There's a good answer to a similar question here and another one here


Would something like this work?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消