简体   繁体   中英

Python file search program not fast enough

I wrote the following code for searching a file on your computer:

import os, sys
import win32api

x=raw_input("Enter file name: ")

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
for drive in drives:
    for folderName, subfolders, filenames in os.walk(drive):
        for filename in filenames:
            if x.upper() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName + ': '+ filename)
            elif x.lower() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName + ': '+ filename)
            elif x.capitalize() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName +': '+ filename)
a=raw_input("Press any key to exit.")
sys.exit()

As you may have noticed this program is not fast enough.

So could anyone help me make a faster and more efficient version of this program?

Thanks!

You can't enhance this program much - any static file search will have to do that sort of thing. By adding a lot of complexity and making it parallel, you could get it to work faster by walking different portions of the file system at a time, and possibly enabling a "lucky hit" earlier.

Applications and utilities that are designed for fast search of the file system usually resort to indexing all file system contents in a database - and they keep doing that either continuously on the background, or at a fixed time of the day. So, when there is aa search,they just perform a query on that database.

This solution however would increase the complexity of your small program several times - and it would be too complex to write here as an answer;

Reducing the number of print statements should increase speed significantly. If you need to trace the files, you could write your results to a log file instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM