Loix0
Loix0

Reputation: 65

Accessing a file relatively in Python if you do not know your starting point?

Hey. I've got a project in Python, whose directory layout is the following:

root
  |-bin
  |-conf
  |-[project]

Python files in [project] need to be able to read configuration data from the 'conf' directory, but I cannot guarantee the location of root, plus it may be used on both Linux, Mac and Windows machines so I am trying to relatively address the conf directory from the root directory.

At the minute it's working with a dirty hack (from root/bin, particular python filename is 8 chars long):

path = os.path.abspath(__file__)[:-8]
os.chdir(path)
os.chdir("..")
[projectclass].config('config/scans.json') #for example

But this is particularly horrid and is giving me nightmares. Is there a better way to accomplish what I'm trying to achieve that doesn't feel so dirty? I feel like I'm missing something very obvious. Thanks in advance.

Upvotes: 0

Views: 87

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881805

Instead of:

path = os.path.abspath(__file__)[:-8]

use:

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

See the docs here.

Upvotes: 2

Related Questions