[Tutor] Running python files
Richard Damon
Richard at Damon-Family.org
Tue Oct 13 21:19:29 EDT 2020
On 10/13/20 8:16 PM, Alan Gauld via Tutor wrote:
> On 14/10/2020 00:28, Phil wrote:
>> This seemingly simple problem has me scratching my head. How do I run a
>> python file from a directory other than the directory that the python
>> file is in?
> There are several ways to do this.
> 1) Use a hard coded full path.
> 2) Put the full path in a config variable in a config file
> 3) Get the path from an environment variable (and have a default if not set)
> 4) change the current working directory to the folder your file is in
> (using the os.chdir() function)
>
> If the location of the file is variable then you might want to bring up
> a dialog to fetch it fom the user, there are various options from the
> curses based dialog module to easy-gui and the tkinter simpledialogs.
> Or just a simple input() call.
>
> You can also ask the program file where it is located if the
> data files are relative to that.
>
> A config file is probably the best option, but then you have
> to find the config file! :-)
>
The way I find the directory the script is running from is:
import os
os.path.dirname(os.path.realpath(__file__))
Note, __file__ is a special name that has the name of the current
script, with path.
--
Richard Damon
More information about the Tutor
mailing list