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


I run a python shell from crontab every minute:

* * * * * /home/udi/foo/

/home/udi/foo has some necessary subdirectories, like /home/udi/foo/log and /home/udi/foo/config, which /home/udi/foo/ refers to.

The problem is that crontab runs the script from a different working directory, so trying to open ./log/bar.log fails.

Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.



Was the most compact elegant solution. Thanks for your answers and explanations!

9/16/2009 1:41:39 PM

Accepted Answer

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

import os

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 os

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

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.

2/10/2012 2:41:53 PM

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



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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow