How can I find script's directory?

PythonDirectoryDjango ViewsGetcwd

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

You need to call os.path.realpath on __file__, so that when __file__ is a filename without the path you still get the dir path:

import os
print(os.path.dirname(os.path.realpath(__file__)))

Solution 2 - Python

Try sys.path[0].

To quote from the Python docs:

>As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

Source: https://docs.python.org/library/sys.html#sys.path

Solution 3 - Python

I use:

import os
import sys

def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

As aiham points out in a comment, you can define this function in a module and use it in different scripts.

Solution 4 - Python

This code:

import os
dn = os.path.dirname(os.path.realpath(__file__))

sets "dn" to the name of the directory containing the currently executing script. This code:

fn = os.path.join(dn,"vcb.init")
fp = open(fn,"r")

sets "fn" to "script_dir/vcb.init" (in a platform independent manner) and opens that file for reading by the currently executing script.

Note that "the currently executing script" is somewhat ambiguous. If your whole program consists of 1 script, then that's the currently executing script and the "sys.path[0]" solution works fine. But if your app consists of script A, which imports some package "P" and then calls script "B", then "P.B" is currently executing. If you need to get the directory containing "P.B", you want the "os.path.realpath(__file__)" solution.

"__file__" just gives the name of the currently executing (top-of-stack) script: "x.py". It doesn't give any path info. It's the "os.path.realpath" call that does the real work.

Solution 5 - Python

import os,sys
# Store current working directory
pwd = os.path.dirname(__file__)
# Append current directory to the python path
sys.path.append(pwd)

Solution 6 - Python

Use os.path.abspath('')

Solution 7 - Python

import os
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep

Solution 8 - Python

This worked for me (and I found it via the this stackoverflow question)

os.path.realpath(__file__)

Solution 9 - Python

Here's what I ended up with. This works for me if I import my script in the interpreter, and also if I execute it as a script:

import os
import sys

# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
    path = os.path.realpath(sys.argv[0])
    if os.path.isdir(path):
        return path
    else:
        return os.path.dirname(path)

Solution 10 - Python

This is a pretty old thread but I've been having this problem when trying to save files into the current directory the script is in when running a python script from a cron job. getcwd() and a lot of the other path come up with your home directory.

to get an absolute path to the script i used

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

Solution 11 - Python

import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]

Solution 12 - Python

Try this:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan LivniView Question on Stackoverflow
Solution 1 - PythonCzarek TomczakView Answer on Stackoverflow
Solution 2 - PythonRED MONKEYView Answer on Stackoverflow
Solution 3 - PythonneuroView Answer on Stackoverflow
Solution 4 - PythonAl CramerView Answer on Stackoverflow
Solution 5 - PythonjbcurtinView Answer on Stackoverflow
Solution 6 - PythonJonathan LivniView Answer on Stackoverflow
Solution 7 - PythonbeoliverView Answer on Stackoverflow
Solution 8 - PythonDan RView Answer on Stackoverflow
Solution 9 - PythonmpontilloView Answer on Stackoverflow
Solution 10 - PythonJamesView Answer on Stackoverflow
Solution 11 - PythonStanView Answer on Stackoverflow
Solution 12 - PythonDaviousView Answer on Stackoverflow