Alex Rivera | Logout

How can I find script's directory?

Asked 2011-02-08T15:14:48.217
703

Consider the following Python code:

import os
print os.getcwd()

I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints /.

How can I get the path to the script from within a script run by a Django view?

UPDATE:
Summing up the answers thus far - os.getcwd() and os.path.abspath() both give the current working directory which may or may not be the directory where the script resides. In my web host setup __file__ gives only the filename without the path.

Isn't there any way in Python to (always) be able to receive the path in which the script resides?

Edit
Report

1 Answer

0
import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]
answered 2011-11-22T16:47:42.467

Your Answer