newbie, relative path

Andrew Dalke dalke at
Thu Nov 1 05:58:05 CET 2001

Marcus Stojek wrote:
>I have a small script that uses an .ini file for configuration. How
>can I open the file config.ini that is in the same dir as the script
>itself? (script dir is changing)

import os, sys

def get_config_filename():
  progname = sys.argv[0]
  dirname = os.path.dirname(progname)
  if dirname == "":
    # run in interactive mode, use current directory
    dirname = os.getcwd()
  return os.path.join(dirname, "config.ini")

print get_config_filename()

 ===== Saved the above into

[dalke at pw600a ~]$ python
[dalke at pw600a ~]$ cd src
[dalke at pw600a ~/src]$ python ../
[dalke at pw600a ~/src]$ python ~/
[dalke at pw600a ~/src]$ python ~/../dalke/
[dalke at pw600a ~/src]$ cd ..
[dalke at pw600a ~]$ python
Python 2.0 (#4, Dec  8 2000, 21:23:00)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> execfile("")

I'm guessing you're trying to reduce the number of configuration
settings needed to run your code, so the directory can be
moved and as long as the program is on the path you can find
the configuration file information.  If so, something else you
can consider is that under unix the file could be on the path
through a symbolic link, so you might want to also try playing
around with os.readlink.  It's trickier than I want to think
about right now though.

                    dalke at

More information about the Python-list mailing list