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?
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()
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?
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()