execute script in certain directory

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 10 01:27:06 CEST 2007

En Mon, 09 Jul 2007 14:14:07 -0300, vasudevram <vasudevram at gmail.com>  

> On Jul 9, 8:31 pm, brad <byte8b... at gmail.com> wrote:
>> When I use idle or a shell to execute a python script, the script
>> executes in the directory it is currently in (in this case, my desktop).
>> However, when using GNOME and right clicking the py script and selecting
>> 'open with python', the execution occurs in my home directory, not my
>> desktop.
> Add these lines to the top of your script:
> import os
> os.chdir(rundir)

I usually don't do that, because it invalidates any filename arguments the  
program may have.
Instead, I use an explicit directory when I want it. For example, to open  
a .dat file located in the same directory as the module using it:

# top of the module
dat_path = os.path.dirname(os.path.abspath(__file__))

# when opening the file
f = open(os.path.join(dat_path, "filename.dat"))

Gabriel Genellina

More information about the Python-list mailing list