Relative path issue in Python

I know this is a simple, beginner question in Python, but I am having problems opening a file using a relative path. This behavior seems strange 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 leads to:

 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, the dir command shows this file on a relative path:

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

What happens with the way Python interprets relative paths in Windows? What is the correct way to open a file with a relative path?

Also , if I transfer my path to 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, it seems that the open() command automatically escapes the \ characters.

** Elimination of the final update: it looks like I mixed up the character in pathanme :) The correct way to do this on Windows seems to use os.path.normpath() , as I did.

+3
source share
1 answer

normpath returns only the normalized version of this particular path. Actually, this does not work to resolve the path for you. You might want to do os.path.abspath(yourpath) .

Also, I assume you are on IronPython. Otherwise, the standard way to express this string format is:

 "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 just the answer to the half-way question. I am puzzled by the complete solution.)

+3
source

All Articles