Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
gaganso Avatar asked May 25 '16 04:05

gaganso


People also ask

How to find the current directory of a file in Python?

Best thing to do is use listdir and getcwd and search in file in the list I think you can use os.walk for iterating the directory and pardir to refer to the parent directory. The pathlib module added in Python 3.4 is well-suited to this task. use listdir to get list of files/folders in current directory and then in the list search for you file.

How to generate file names in a directory tree in Python?

Create a function that uses os.walk method we will do it in Pictures directory. So will either already choose a file in the directory or use one of the folders available there. Python method walk () generates the file names in a directory tree by walking the tree either top-down or bottom-up.

How do I search for a file in a directory?

In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\”. The os.walk () function searches the entire directory and each of its subdirectories to locate this file.

How do I find the location of a file in Python?

The os.walk () function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory.


3 Answers

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
like image 129
Harwee Avatar answered Oct 12 '22 23:10

Harwee


Another option, using pathlib:

from pathlib import Path


def search_upwards_for_file(filename):
    """Search in the current directory and all directories above it 
    for a file of a particular name.

    Arguments:
    ---------
    filename :: string, the filename to look for.

    Returns
    -------
    pathlib.Path, the location of the first file found or
    None, if none was found
    """
    d = Path.cwd()
    root = Path(d.root)

    while d != root:
        attempt = d / filename
        if attempt.exists():
            return attempt
        d = d.parent

    return None
like image 39
martinhans Avatar answered Oct 13 '22 00:10

martinhans


Here's another one, using pathlib:

from pathlib import Path


def find_upwards(cwd: Path, filename: str) -> Path | None:
    if cwd == Path(cwd.root):
        return None
    
    fullpath = cwd / filename
    
    return fullpath if fullpath.exists() else find_upwards(cwd.parent, filename)
    
    
find_upwards(Path.cwd(), "helloworld.txt")

(using some Python 3.10 typing syntax here, you can safely skip that if you are using an earlier version)

like image 23
David Vujic Avatar answered Oct 13 '22 00:10

David Vujic