Python Forum

Full Version: automatically get absolute paths
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I want to automatically convert relative paths to absolute paths.


dirname = os.path.dirname(__file__)
os.path.join(dirname, r'relative/path/file.txt')

This worked fine but I used this in several places so I thought it makes sense to put it in a separate module. So I did. But when I import it, __file__ points to the module, not to the calling file.

I could give __file__ as an argument enverytime I call that function but it would be easier if I don't have to do that. Any ideas?

Thats the (very simple) function:
import os
def AbsPath(relPath):
    dirName = os.path.dirname(__file__)
    absPath = os.path.join(dirName, relPath)
    return absPath
I use a trick similar to this in small programs that use an image or sound file. Get the path to the local file and use that as the base for the files you want to open. I'm pretty sure there is no way to make it work the same way as an imported module. It's a bit of a hack anyway.

That doesn't mean it isn't useful at all. If you put your files in the same folder as this module it will work. For example, you have a folder containing all your image files and you want a simple way to get an image file. Write a version of this named imagefiles.py.
import os
DIRECTORY = os.path.dirname(__file__)

def get(relPath):
    return os.path.join(DIRECTORY, relPath)
From your program that uses image files.
import imagefile
abs_path = image_file.get('ship.png')