2

I need a constant for a file(database) path, as a base_directory. I know there are no real constants in python.

I set this way:

base_dir = (os.getcwd().rsplit('\\', 2)[0],)

I need this value in multiple files, in different directories/folders levels/depths. So I created a file with variables and I import the file where is needed.

The problem is that the base_dir is not calculated based were is the location(path) of the imported file, but based on the location of the current file.

So I have different paths based on the path depth.

I can change every time the base_dir to adapt to the new path, but I need to repeat not only the var declaration but a lot of related code for every file.

How can this be fixed, simulating a constant for a path?

demongolem
  • 9,474
  • 36
  • 90
  • 105
user3541631
  • 3,686
  • 8
  • 48
  • 115

1 Answers1

3

No need to use os.getcwd. Get your constants file path with os.path.abspath:

file_abs_path = os.path.abspath(os.path.dirname(__file__))

And build path to database file with os.path.join:

database_path = os.path.join(file_abs_path, '..', 'path', 'to', 'db)

Then import constants and access constants.database_path.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82