mystack
mystack

Reputation: 5492

Find the path to a file in an unknown directory

I have a python file to print the full path of another file that can be in one of some other directories. My folder structure is given below:

D:\Main\Script\Myscript.py
D:\Main\Target\A\cow.txt
D:\Main\Target\B\dog.txt,p1.txt
D:\Main\Target\c\cat.txt
D:\Main\Target\D\Q1.txt

When I give the filename, I want to print the fullpath of that file. For example if I give "Q1.txt" it should print D:\Main\Target\D\Q1.txt. I tried the following, let my input file be Myfile1.

Scriptloc=os.path.join(os.path.dirname(__file__))
if (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1)):
   print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1)):
   print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+B+Myfile1
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1)):
   print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+D+Myfile1)):
   print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1
else:
   print "File not found"

Is there any other easy way to do this?

Upvotes: 0

Views: 4038

Answers (2)

Mike McKerns
Mike McKerns

Reputation: 35207

you could use pox, which is built to navigate directories and work with filesystem manipulation

>>> from pox.shutils import find
>>> find('Q1.txt')
['/Users/mmckerns/Main/Target/D/Q1.txt']

The above can be run from any directory, and you can specify a directory root to start from. It will find all files names Q1.txt, and return their full paths. There are options to search for directories, and to ignore soft links, and all sorts of other stuff. The search is a fast search, much like unix's find function. Failing, pox.shutils.find will failover to python's os.walk (much slower)… which is what you could use if you wanted to stay within the standard library for whatever reason.

get pox here: https://github.com/uqfoundation

Upvotes: 2

bereal
bereal

Reputation: 34272

You could use os.walk, for example:

def find_file(basedir, filename):
    for dirname, dirs, files in os.walk(basedir):
        if filename in files:
            yield os.path.join(dirname, filename)

for found in find_file(basedir, 'Q1.txt'):
    print found

That way you don't have to hardcode your folder structure.

Upvotes: 2

Related Questions