Python 3 minor irritation

Benjamin Kaplan benjamin.kaplan at
Thu Feb 4 04:14:59 CET 2010

On Wed, Feb 3, 2010 at 9:56 PM, Alf P. Steinbach <alfps at> wrote:
> * David Monaghan:
>> I have a small program which reads files from the directory in which it
>> resides. It's written in Python 3 and when run through IDLE or PythonWin
>> works fine. If I double-click the file, it works fine in Python 2.6, but
>> in
>> 3 it fails because it looks for the files to load in the Python31 folder,
>> not the one the script is in.
>> It's not a big deal, but browsing around I haven't found why the behaviour
>> has been changed or any comment about it (That might be my poor search
>> technique, I suppose).
>> The program fails at:
>>    try:
>>        tutdoc = minidom.parse(".//Myfile.xml")
>>    except IOError:
>>        <snip>
> The "//" is wrong, but should not cause the behavior that you describe.
> Try to post a complete smallest possible program that exhibits the problem.
> Possibly, in creating that example you'll also find what's cause the
> problem. :-)
> Cheers & hth.,
> - Alf

That is the smallest example the exhibits the problem. It's not an
issue with the Python code, it's an issue with how Windows is running
it. I don't know enough about the way Windows Explorer runs files, but
it seems to be doing the equivalent of
cd C:\Python31
python31.exe C:\full\path\to\script\

instead of
cd C:\full\path\path\to\script
which is David expected. This throws off the relative filepath.

The easiest way to solve this permanently, by the way, is to not use
relative paths. All it takes is one script to call os.chdir and the
script breaks. You can use __file__ and the os.path module to figure
out exactly where you are in an OS-agnostic way.

import os.path
#get the absolute path to the current script
abs_path = os.path.abspath(__file__)

 # get the full path to the directory of the script
directory = os.path.dirname(abs_path)

#get the full path to your file
my_file = os.path.join(directory, "MyFile.xml")

> --

More information about the Python-list mailing list