Search code examples
pythonpython-3.xpython-2.7

Python: search for a file in current directory and all its parents


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

Without such a 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?


Solution

  • 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
    import os.path
    
    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
            break
        else:
            if cur_dir == parent_dir: #if dir is root dir
                print "File not found"
                break
            else:
                cur_dir = parent_dir