Best way to find starting directory

Frank Millman frank at chagford.com
Tue Mar 19 09:21:27 CET 2013


On 19/03/2013 09:55, Peter Otten wrote:
> 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
>
>

That makes sense. I usually launch the script from its own directory, 
but that is not guaranteed.

Therefore option 2 is the way to go.

Thanks, Peter

Frank





More information about the Python-list mailing list