tags:

views:

1364

answers:

1

I know this is a simple, beginner-ish Python question, but I'm having trouble opening a file using a relative path. This behavior seems odd to me (coming from a non-Python background):

import os, sys

titles_path = os.path.normpath("../downloads/movie_titles.txt")

print "Current working directory is {0}".format(os.getcwd())
print "Titles path is {0}, exists? {1}".format(movie_titles_path, os.path.exists(movie_titles_path))

titlesFile = open(movie_titles_path, 'r')
print titlesFile

This results in:

C:\Users\Matt\Downloads\blah>testscript.py

Current working directory is C:\Users\Matt\Downloads\blah
Titles path is ..\downloads\movie_titles.txt, exists? False

Traceback (most recent call last):
  File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module>
    titlesFile = open(titles_path, 'r')
IOError: [Errno 2] No such file or directory: '..\\downloads\\movie_titles.txt'

However, a dir command shows this file at the relative path exists:

C:\Users\Matt\Downloads\blah>dir /b ..\downloads\movie_titles.txt
movie_titles.txt

What's going on with how Python interprets relative paths on Windows? What is the correct way to open a file with a relative path?

Also, if I wrap my path in os.path.abspath(), then I get this output:

Current working directory is C:\Users\Matt\Downloads\blah
Titles path is C:\Users\Matt\Downloads\downloads\movie_titles.txt, exists? False
Traceback (most recent call last):
  File "C:\Users\Matt\Downloads\blah\testscript.py", line 27, in <module>
    titlesFile = open(titles_path, 'r')
IOError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\Downloads\\downloads\\movie_titles.txt'

In this case, seems like the open() command is automatically escaping the \ characters.

**Embarrassing final update: Looks like I munged a character in the pathanme :) The correct way to do this on Windows seems to be to use os.path.normpath(), as I did originally.

+1  A: 

normpath only returns a normalized version of that particular path. It does not actually do the work of resolving the path for you. You might want to do os.path.abspath(yourpath).

Also, I'm assuming you're on IronPython. Otherwise, the standard way of expressing that string format would be:

"Current working directory is %s" % os.getcwd()
"Titles path is %s, exists? %s" % (movie_titles_path, os.path.exists(movie_titles_path))

(Sorry, this is only an answer to the halfway posted question. I'm puzzled about the full solution.)

Paul Fisher
Using the Python 2.6 Windows installer from python.org
matt b
I didn't know about the new string formatting in Py26 then. Good to learn :)
Paul Fisher