[Tutor] Running python files

alexkleider alexkleider at protonmail.com
Wed Oct 14 00:34:25 EDT 2020


‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Tuesday, October 13, 2020 6:19 PM, Richard Damon <Richard at Damon-Family.org> wrote:

> 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.

I think I've understood the OP's problem and the solutions offered and have come up with the following (trivial) example that I believe provides a way of solving the problem.
No matter from where the script (to_try.py) is run, as long as helpers.py and txt.txt are in the same directory as to_try.py, it all seems to work.

#!/usr/bin/env python3

# File: to_try.py

import os
import helpers
# The way I find the directory the script is running from is:
print(os.path.dirname(os.path.realpath(__file__)))
dirname = os.path.dirname(os.path.realpath(__file__))
file_I_want = 'txt.txt'
file_name = os.path.join(dirname, file_I_want)
# Note, __file__ is a special name that has the name of the
# current script, with path.
with open(file_name, 'r') as instream:
    data = instream.read()
print(data)


Hope this helps to solve the OP's dilemma.
Comments, critiques, ... welcome


More information about the Tutor mailing list