How to get the path from content root in python?

Question:

Suppose that I have a working directory called directory 1. This directory has an app.py file and a directory file called directory2. Inside directory2 I have a text file called example.txt.

Is there a way of finding the path of example.txt using a command in app.py, knowing only the name of the text file and that it exists inside some directory of my working directory?

Asked By: CoolMathematician

||

Answers:

OS.walk() is what you are after.

Demo

import os

def find_file():
    for root, dirs, files in os.walk(os.getcwd()):
        if 'example.txt' in files:
            path = os.path.join(root, 'example.txt')
            print(f'file exists at {path}')
            return
    print('file does not exist')

find_file()
Answered By: cdy_peters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.