Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to do a system wide search for a file when just the filename (not path) is available

Tags:

python

search

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.

Thanks.

like image 960
ldmvcd Avatar asked Mar 01 '11 10:03

ldmvcd


2 Answers

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

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
like image 110
Martin Stone Avatar answered Sep 20 '22 10:09

Martin Stone


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

like image 21
Peter Kelly Avatar answered Sep 21 '22 10:09

Peter Kelly