tags:

views:

44

answers:

1

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.

+2  A: 

Instead of:

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

use:

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

See the docs here.

Alex Martelli
Damn, can't believe I missed that. My excuse is it's late here!Still feels dirty though!
Loix0
@Loix0, can you articulate what feels "dirty" to you about it? `__file__` tells you "where you are", so that's where you navigate from. Maybe use `os.path.join` instead of `os.chdir`, if it's only a file or two you need to read from directory `conf`...?
Alex Martelli
It's not dirty at all. It's using *__file__* as it is intended to be used.
Brian Clapper
@Brian, good to know.@Alex, I think that's what I thought was dirty about it, that I was using __file__ for something it wasn't intended for, or what I was doing wasn't good practice (although for what this little project is intended for, 'good practice' isn't at the top of my list of priorities).As long as no one has immediately come back with "OMG u noob wtf!!1one" I guess I'll have to live with it.
Loix0