Objective: I am trying to find the absolute path of a specific filename.
Scenario: My script is executing from within some (great-great-grand)-parent directory, and my file is somewhere in that same (great...)-parent directory.
Problem:
E:
├───Directory
│ └───Sub Directory
└───Grandparent Folder
├───Parent Directory
│ └───script.py
└───Other Parent Directory
└───MyFile.txt
The great-parent directory is getting moved around frequently. So the parent directories absolute path is not known.
The script is getting moved around a lot within the great-parent directory and changing file levels within that directory, so I can't just use
'../../..'
to get up to the parent directory.The file I'm looking for gets moved around alot within the great-parent directory.
Once I have the absolute path of the parent directory, I can just os.walk()
around to find my file.
Attempt: What I have below works, but I have to imagine this a common enough problem to have a built-in os
command that I don't know about.
import os
parent_folder = 'Grandparent Folder'
search_file = 'MyFile.txt'
# Get absolute path of grandparent directory.
current_path = os.getcwd()
parent_path = current_path.split(parent_folder)[0] + parent_folder
# os.walk() from grandparent down until file is found.
filepath= ''
for root, dirs, files in os.walk(parent_path):
for file in files:
if file == search_file:
filepath = '\\'.join([root, file])