Home > Mobile >  Relative path fails in a submodule
Relative path fails in a submodule

Time:02-17

I have a python project A, this project is distributed to clients as-is. Inside project A I use hard coded paths to files in this project (w.r.t its working directory). Let's say I have a db file in project A located under resources/employees.db

I also have project B, which is also distributed to clients. in project B, project A is listed as a git submodule, located in folder projectA, when I try to start project B it fails, as it can't initialize project A due to unfound file:

FileNotFoundError: [Errno 2] No such file or directory: 'resources/employees.db'

It makes sense, w.r.t to the working directory of project B, the file should be loaded from projectA/resources/employees.db. But of course changing this relative path in project A is not acceptable. How to solve this conflict?

CodePudding user response:

You can use a path relative to the current Python file, whose absolute path is helpfully provided for you in the __file__ global. For example:

import os.path

EMPLOYEES_DB_PATH = os.path.join(
    os.path.dirname(__file__),
    '..', 'resources', 'employees.db')

Adjust the number of '..' entries according to the location of this Python file.

  • Related