Reading a file in same directory as code with relative path

manuelg at gmail.com manuelg at gmail.com
Fri Nov 18 23:41:43 CET 2005


Answer to a similar question:

http://groups.google.com/group/comp.lang.python/msg/c01f292d7926f393?hl=en&

If you want a way that will work regardless if your module is run
interactively, imported, or just run by itself, this is a solution that
will always work:

:: \wherever\wherever\     (the directory your module is in,
                            obviously somewhere where PYTHONPATH can
                            see it)

:::: danmodule.py          (your module)

:::: danmodule_xml\        (a subdirectory in the same directory as
                            your module;
                            it will only have 2 files in it)

:::::: __init__.py         (an empty textfile in danmodule_xml\,
                            only here to make danmodule_xml\
                            work like a package)

:::::: data.xml            (your xml file in danmodule_xml\)

Here is the Python code for loading the file:

# ################ #
import xml.dom.minidom
import os.path
import danmodule_xml

xml_data_path = os.path.split(danmodule_xml.__file__)[0]

xml_file_fullpath = os.path.join(xml_data_path, 'data.xml')

document = xml.dom.minidom.parse(xml_file_fullpath)
# ################ #

Obviously, if you have more than 1 xml files, just put them all in
"danmodule_xml\".




More information about the Python-list mailing list