"Directory this source file is in (and a sibling)"

S

Sion Arrowsmith

I have a module which needs to know what directory it's in, and to
refer to files in a sibling directory, something like App/src/foo.py
wants to read App/data/conf.xml . But I have no idea in what context
foo.py is going to be run -- it could be being run as a script, it
could be being imported as a module by another script from anywhere in
the directory structure, it's even possible someone will have called
execfile on it. The following works for everything I've tried:

thisdir = os.path.dirname(os.path.normpath(__file__))
siblingdir = os.path.normpath(os.path.join(testdir, os.path.pardir, "sibling"))

However, a colleague expressed disgust at this code, but not really
being a Python programmer had no better suggestions. Is there a neater
way of getting what I want?
 
J

John Machin

Sion said:
I have a module which needs to know what directory it's in, and to
refer to files in a sibling directory, something like App/src/foo.py
wants to read App/data/conf.xml . But I have no idea in what context
foo.py is going to be run -- it could be being run as a script, it
could be being imported as a module by another script from anywhere in
the directory structure, it's even possible someone will have called
execfile on it. The following works for everything I've tried:

thisdir = os.path.dirname(os.path.normpath(__file__))
siblingdir = os.path.normpath(os.path.join(testdir, os.path.pardir, "sibling"))

However, a colleague expressed disgust at this code, but not really
being a Python programmer had no better suggestions. Is there a neater
way of getting what I want?

If you plan to have your code executed out of a zip or an egg, you may
have problems because __file__ is not what you want, at least with eggs
and Python 2.[34]. There was a brief thread on this topic on the
distutils SIG mailing list within the last few days.

HTH,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top