SilentMonk SilentMonk - 1 year ago 108
Python Question

Python: search for a file in current directory and all it's parents

Is there an inbuilt module to search for a file in the current directory, as well as all the super-directories?

Without the module, I'll have to list all the files in the current directory, search for the file in question, and recursively move up if the file isn't present. Is there an easier way to do this?

Answer Source

Well this is not so well implemented, but will work

use listdir to get list of files/folders in current directory and then in the list search for you file.

If it exists loop breaks but if it doesn't it goes to parent directory using os.path.dirname and listdir.

if cur_dir == '/' the parent dir for "/" is returned as "/" so if cur_dir == parent_dir it breaks the loop

import os

file_name = "test.txt" #file to be searched
cur_dir = os.getcwd() # Dir from where search starts can be replaced with any path

while True:
    file_list = os.listdir(cur_dir)
    parent_dir = os.path.dirname(cur_dir)
    if file_name in file_list:
        print "File Exists in: ", cur_dir
        if cur_dir == parent_dir: #if dir is root dir
            print "File not found"
            cur_dir = parent_dir
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download