Best way to find starting directory

Peter Otten __peter__ at web.de
Tue Mar 19 03:55:45 EDT 2013


Frank Millman wrote:

> I want to locate a file relative to the directory from which the main
> program was launched.
> 
> I have found two ways of finding the starting directory -
> 
> 1.
> import os
> dir = os.getcwd()

This gives the current working directory... 

> 2.
> import os.path
> import __main__
> dir = os.path.dirname(__main__.__file__)

... and this gives the location of your main script.
 
> I know that the first one will return the wrong result if os.chdir() has
> been executed, but I don't do that.

You'll get different results when you launch the script with an explicit 
path:

$ cat millman/demo.py
import os
import __main__

print "cwd:", os.getcwd()
print "script path:", os.path.abspath(os.path.dirname(__main__.__file__))
$ python millman/demo.py 
cwd: /home/frank
script path: /home/frank/millman





More information about the Python-list mailing list