Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative paths in Python

I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?

like image 545
baudtack Avatar asked May 27 '09 21:05

baudtack


People also ask

What is the relative path in Python?

A relative path that depicts the location of a file or folder is relative to the current working directory. Unlike absolute paths, relative paths contain information that is only relative to the current document within the same website, which avoids the need to provide a full absolute path.

Can you use relative paths in Python?

relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.

What is a relative path?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


1 Answers

In the file that has the script, you want to do something like this:

import os dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'relative/path/to/file/you/want') 

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py import os print os.getcwd() print __file__  #in the interactive interpreter >>> import foo /Users/jason foo.py  #and finally, at the shell: ~ % python foo.py /Users/jason foo.py 

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5 >>> collections.__file__ '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib- dynload/collections.so' 

However, this raises an exception on my Windows machine.

like image 145
Jason Baker Avatar answered Sep 25 '22 13:09

Jason Baker