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.