python: Change the scripts working directory to the script's own directory python: Change the scripts working directory to the script's own directory python python

python: Change the scripts working directory to the script's own directory


This will change your current working directory to so that opening relative paths will work:

import osos.chdir("/home/udi/foo")

However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path functions:

import osabspath = os.path.abspath(__file__)dname = os.path.dirname(abspath)os.chdir(dname)

This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.


You can get a shorter version by using sys.path[0].

os.chdir(sys.path[0])

From http://docs.python.org/library/sys.html#sys.path

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


Don't do this.

Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages or /var/opt/udi or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.

Bottom line: Do not mingle code and data.

Data is precious. Code comes and goes.

Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)

Make it a required argument value and do this.

import sysimport osworking= os.environ.get("WORKING_DIRECTORY","/some/default")if len(sys.argv) > 1: working = sys.argv[1]os.chdir( working )

Do not "assume" a directory based on the location of your software. It will not work out well in the long run.