Python:当只有文件名(而非路径)可用时,如何在系统范围内搜索文件

时间:2022-06-19 16:56:55

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 looked 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.

我还是Python新手(使用2.6版本),我正在尝试在系统范围内搜索文件,只要文件名可用并返回windows上的绝对路径。我搜索并发现了一些模块,比如scriptutil。py浏览了os模块,但是没有找到任何适合我需要的东西(或者我可能没有正确理解所有的东西来应用它到我需要的地方,因此没有包含任何代码)。我希望得到任何帮助。

Thanks.

谢谢。

3 个解决方案

#1


16  

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

操作系统.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

#2


4  

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

这里有一个类似问题的好答案,这里有一个

#3


0  

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

#1


16  

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

操作系统.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

#2


4  

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

这里有一个类似问题的好答案,这里有一个

#3


0  

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