1

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
  1. The great-parent directory is getting moved around frequently. So the parent directories absolute path is not known.

  2. 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.

  3. 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])
Michael Molter
  • 1,296
  • 2
  • 14
  • 37

1 Answers1

0

Try using pythons glob module to find the pathname. You can find details on official documentation. That way even if the directory moves, you can find the path every time.

  • Does this help me find my grandparent directory, or just the file once I have the parent directory? – Michael Molter May 16 '17 at 16:29
  • You can use it to find both as long as you know the script name or the file name (these should be unique else there might be multiple matches) – Srikkanth Govindaraajan May 16 '17 at 17:41
  • @MichaelMolter: You could also use a combination of fnmatch() and glob() Refer to this SO question - http://stackoverflow.com/questions/14798220/how-can-i-search-sub-folders-using-glob-glob-module-in-python Once you find the file, you can return the working directory. – Srikkanth Govindaraajan May 16 '17 at 17:57
  • I don't think this approach addresses the heart of the problem. It is an easier way to grab the specific file once I find the parent directory, but it in no way helps me find the parent directory? – Michael Molter May 16 '17 at 18:53