Reputation: 11785
for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following
sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))]
this seems a touch ridiculous, surely there is a simpler way?
Upvotes: 3
Views: 613
Reputation: 26111
I've found Jason Orendorff's path module to be very nice. Unfortunately, it seems that his website is no longer on the internet, but you can still download the module from PyPI.
Upvotes: 2
Reputation: 20878
If it is a huge problem, you could wrap os.path functionality is a path class. I'm pretty sure there is a Path module floating around on the internet.
Upvotes: 0
Reputation: 304393
Another option is to import path from os. It's not the most consise but I think it's still easy to read. Do you really want us to golf it? :)
from os import path
sys.path += [path.dirname(path.dirname(path.realpath(__file__)))]
Upvotes: 0
Reputation: 342819
you can also do this
>>> from os.path import dirname as dn, realpath as rp
but its still better to explicitly define the name so you won't have variable names collision problems.
Upvotes: 1
Reputation: 53320
You could do:
from os.path import dirname,realpath
sys.path.append(dirname(dirname(realpath(__file__))))
But to be honest, I prefer the full explicit version. It's much easier to read as a standalone statement.
Upvotes: 1