80

Say I have a python file in directory e like this:

/a/b/c/d/e/file.py

Under directory e I have a few folders I want to access but if file.py is executed from anywhere else rather than from folder e the relative path won't work for me. Also folder e could be located anywhere but always with the a set of sub folders so absolute path will not work.

First, is there any function to get the absolute path in relation to the source files location?

If not, any ideas how to sort this out? Grab the command line used and add the CWD together?

My problem here is that this folder are being installed on 20 different machines and OS's and I want it to be as dynamic as possible with little configurations and "rules" where it has to be installed etc.

StefanE
  • 7,578
  • 10
  • 48
  • 75
  • Question "How to retrieve a module's path?" is a different question. Unless a person who closed this question would explain how to get it for current file. – Petr Gladkikh Jun 15 '23 at 12:27

3 Answers3

119
# in /a/b/c/d/e/file.py
import os
os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e
Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
19

In Python +3.4 use of pathlib is more handy:

from pathlib import Path

source_path = Path(__file__).resolve()
source_dir = source_path.parent
Marek R
  • 32,568
  • 6
  • 55
  • 140
  • 1
    Changed the correct answer to this as its more up to date then when I asked this more than 10 years ago :) – StefanE Jan 24 '22 at 09:58
9

Here is my solution which (a) gets the .py file rather than the .pyc file, and (b) sorts out symlinks.

Working on Linux, the .py files are often symlinked to another place, and the .pyc files are generated in the directory next to the symlinked py files. To find the real path of the source file, here's part of a script that I use to find the source path.

try:
    modpath = module.__file__
except AttributeError:
    sys.exit('Module does not have __file__ defined.')
    # It's a script for me, you probably won't want to wrap it in try..except

# Turn pyc files into py files if we can
if modpath.endswith('.pyc') and os.path.exists(modpath[:-1]):
    modpath = modpath[:-1]

# Sort out symlinks
modpath = os.path.realpath(modpath)
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • 1
    This was never actually a particularly thorough solution: you could have .pyo files instead of .pyc files too (though that was never *popular*). And now in Python 3 the .pyc files go in a `__pycache__` directory rather than next to the .py files, so the solution is basically completely broken now on Py3K. – Chris Morgan Aug 04 '18 at 15:02
  • Thank you for your feedback. In python3 it works, as the `__file__` seems to be always the real `.py` path. – mvorisek Aug 04 '18 at 15:08