使用 Python 在所有驱动器中搜索文件 [英] search files in all drives using Python

查看:45
本文介绍了使用 Python 在所有驱动器中搜索文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python,我需要一个函数或库来在所有驱动器中搜索我的文件,我在 Windows 中仅将文件名设为 F3 以搜索计算机中的所有文件夹.windows os , 本地驱动器 , 我写了一段代码

I work with python and I need a function or library that search for my files in all drives, that I give it just the name of files as F3 in Windows that search on all folders in computer. windows os , local drives ,, i write a code

import os
import win32api
paths = 'D:/'
def dir_list_folder(paths):
    for folderName in os.listdir(paths):
        if (folderName.find('.') == -1):
            folderPath = os.path.join(paths,folderName );
            dir_list_folder(folderPath);
        else:
            print ('Files is :'+ folderName );

它给了我一个很好的结果,但有些类型给了我一个错误,如果我不需要在 .Zip 或 .RAR 文件中搜索,我该怎么做

it give me a good result but some type is give me an error , if i don't need to search in .Zip or .RAR file how i can do that

推荐答案

在 Windows 上,最好使用 os.walk 函数.os.walk 返回一个递归遍历源树的生成器.下面的示例显示了正则表达式搜索.

On Windows, you will be better off using the os.walk function. os.walk returns a generator that recursively walks the source tree. The sample below shows a regular expression search.

import os
import re
import win32api

def find_file(root_folder, rex):
    for root,dirs,files in os.walk(root_folder):
        for f in files:
            result = rex.search(f)
            if result:
                print os.path.join(root, f)
                break # if you want to find only one

def find_file_in_all_drives(file_name):
    #create a regular expression for the file
    rex = re.compile(file_name)
    for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
        find_file( drive, rex )


find_file_in_all_drives( 'myfile\.doc' )

一些注意事项:

  1. 我正在使用正则表达式来搜索文件.为此,我提前编译了 RE,然后将其作为参数传递.请记住对表达式进行规范化 - 特别是在文件名来自恶意用户的情况下.
  2. win32api.GetLogicalDriveStrings 返回一个字符串,其中所有驱动程序以 0 分隔.拆分它,然后切出最后一个元素.
  3. 在漫游过程中,您可以从目录"中删除不需要的文件夹,例如.git"或.cvs".例如,请参见 os.walk.__doc__.
  4. 为了保持样本简短,我没有传播找到".如果要打印所有文件,请删除 break.如果您想在找到第一个文件后停止,请将 break 传播到 find_file_in_all_drives.
  1. I'm using a regular expression for searching the file. For this, I'm compiling the RE ahead of time and then pass it as an argument. Remember to normalize the expression - especially if the file name is coming from a malicious user.
  2. win32api.GetLogicalDriveStrings returns a string with all drivers separated by 0. Split it and then slice out the last element.
  3. During the walk, you can remove unwanted folders from 'dirs' such as '.git' or '.cvs'. See os.walk.__doc__, for example.
  4. To keep the sample short, I did not propagate 'found'. Remove the break if you want to print all files. Propagate the break to find_file_in_all_drives if you want to stop after the first file has been found.

这篇关于使用 Python 在所有驱动器中搜索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆