Reading a file in same directory as code with relative path

Bengt Richter bokr at oz.net
Fri Nov 18 00:12:43 EST 2005


On 17 Nov 2005 17:29:55 -0800, dan.j.weber at gmail.com wrote:

>I'm trying to read an XML file in the same directory as my python code,
>using minidom:
>
>document = xml.dom.minidom.parse("data.xml")
>
>How can I read in the file "data.xml" without knowing it's full
>path--just that it's in the same directory as my code file? Thanks for
>any help with this. I'm new to python and really liking it so far.
>

----< showmydir.py >------------
import os
print dir()
print __file__
print os.path.abspath(__file__)
print os.path.dirname(os.path.abspath(__file__))
print os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.xml')
--------------------------------

When run, outputs (in my directory context):

[21:07] C:\pywk\clp>py24 showmydir.py
['__builtins__', '__doc__', '__file__', '__name__', 'os']
showmydir.py
C:\pywk\clp\showmydir.py
C:\pywk\clp
C:\pywk\clp\data.xml

If I go somwhere else and execute it, e.g. from a sibling directory

[21:08] C:\pywk\grammar>py24 ..\clp\showmydir.py
['__builtins__', '__doc__', '__file__', '__name__', 'os']
..\clp\showmydir.py
C:\pywk\clp\showmydir.py
C:\pywk\clp
C:\pywk\clp\data.xml

(Hm, that's an interesting outcome for __file__ )

HTH

Regards,
Bengt Richter



More information about the Python-list mailing list