2

What is the best practice to get the path of the currently executed script?

path = os.path.dirname(os.path.abspath(__file__))

or

path = __path__[0]

When tried, they both output the same result.
But is one more rigorous than the other?
Is one more cross platform?

The doc says:

This variable can be modified; doing so affects future searches for modules and subpackages contained in the package. While this feature is not often needed, it can be used to extend the set of modules found in a package.

Apart from me modifying it explicitly, can it be modified by the interpreter without me knowing?
If so, would that return a wrong path, or is the first element always pointing to the current directory of the script?

I need that to access a config file which would be stored inside a folder called config/ in my package.
But open("config/config.txt", 'rt') does not work, it returns a IOError: [Errno 2] No such file or directory

Thanks.

Bruno
  • 33
  • 2
  • 1
    Only [packages have a `__path__`](http://docs.python.org/3/reference/import.html#__path__), and it can be empty. Only Python 3.4 now guarantees that values in `__path__` are set to absolute paths. – Martijn Pieters Mar 30 '14 at 14:54
  • possible duplicate of [How do I get the path of the current executed file in python?](http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python) – m.wasowski Mar 30 '14 at 14:55
  • You can use `realpath` i.o. `abspath` if you want to resolve symlinks etc. – jamadagni Apr 02 '14 at 06:39

0 Answers0