【问题标题】:search files in all drives using Python [closed]使用 Python 在所有驱动器中搜索文件 [关闭]
【发布时间】:2012-10-25 11:34:00
【问题描述】:

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

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 文件中搜索,我该怎么做

【问题讨论】:

  • 请先自己尝试,然后再询问您无法克服的任何特殊问题。
  • 您能否更准确地了解您的需求,您的操作系统是什么,所有驱动器是什么意思:所有本地驱动器、网络共享磁盘?
  • @silent_warrior 查看编辑问题
  • @FabienAndre 查看编辑问题

标签: python python-2.7


【解决方案1】:

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

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

【讨论】:

  • win32api.GetLogicalDriveStrings()+1。
  • 好的,谢谢你的回答,效果很好
  • @Uri : 我对代码有一点疑问,它并没有给我所有的结果,是什么原因?
  • @D.Jo - 我没有测试代码,但它应该可以工作。您是否按原样使用示例代码?你的正则表达式有错误吗?你有符号链接吗?请随时与我联系(我在个人资料中的电子邮件地址)。
  • @Uri 按原样使用示例代码,只需将我需要的文件名更改为 '.txt' 只是为了获取目录中的所有 .txt 文件,它可以工作,但并没有给我全部。 txt文件
【解决方案2】:
import os
az = lambda: (chr(i)+":\\" for i in range(ord("A"), ord("Z") + 1))
for drv in az():
    for root, dirs, files in os.walk(drv):
        process_the_stuff()

【讨论】:

    【解决方案3】:

    您需要指定驱动器,例如 c 驱动器。

    def findall(directory):
        files=os.listdir(directory)
        for fl in files:
            path=os.path.join(directory,fl)
            if os.path.isdir(path):
                findall(path)
            else:
                dosomethingwithfile(path)
        return
    

    基本上你遍历文件树。您必须将驱动器作为根目录传递给此方法。例如。 findall('c:/')

    【讨论】:

    • 谢谢,但 {os.path.isdir(directory+'/'+fl)} 不能正常工作
    • @D.Jo 为什么不呢?
    • @specialscope 在for 行之后添加path = os.path.join(directory, fl) 并将所有directory+'/'+fl 替换为path
    • 它在文件夹内搜索很好,但它也在文件内搜索,如果是文件,则应该停止,而不是搜索
    猜你喜欢
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多