python - Search all drives for a file -


i have name of file , want find on whatever drive is. can use recursive search, need root directory start with. computers, root "c:\". there have changed letter, or have more 1 (eg. c,d...).

so, need find way know drives in computer, can search through each one. need find letters programmatically without user input.

i know can use "diskpart", requires administrator access, code not have. there "wmic", don't know if computer has right folder in path.

so, question how can recursive search in computer don't know letters of drives or how many there? or there way find path of file in computer?

i have solution requires run administrator, not require install other tools. have alternative, messy solution can run without of these privileges. i'll start cleaner one.

this script find drives:

import subprocess  drivestr = subprocess.check_output("fsutil fsinfo drives") drivestr = drivestr.strip().lstrip('drives: ') drives = drivestr.split() 

basically, fsutil fsinfo drives commandline command return letters of existing drives on computer. can result check_output , strip away unnecessary characters, because return string '\r\ndrives: c:\\ d:\\ \r\n'. can split list , you'll have list of drives this:

['c:\\', 'd:\\'] 

you can loop on drives recursively search file.

import os  def find_file(target, folder):     f in os.listdir(folder):         path = os.path.join(folder, f)         if os.path.isdir(path):             result = find_file(target, path)             if result not none:                 return result             continue         if f == target:             return path 

this function loop on every file in folder it's provided, first checks if file folder isdir, , runs recursively on folders finds. if it's not folder, check file named target , return path when found. can combine these 2 parts pretty simply:

for drive in drives:     filepath = find_file(target, drive)     if filepath not none:         break 

however, if you're unable run administrator, there way that's not nice. loop on possible drive names , check if exist, this:

drives = ['{}:\\' letter in 'cdefghijklmnopqrstuvwxyz'] drive in drives:     if os.path.isdir(drive):         filepath = find_file(target, drive)         if filepath not none:             break 

this check if each drive exists directory , search each 1 does. note include networked paths , believe usbs/external hard drives, while alternative method not.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -