Python中的相对path问题

我知道这是一个简单的,初学者是Python的问题,但我无法打开使用相对path的文件。 这种行为似乎很奇怪(来自非Python背景):

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 

这导致:

 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' 

但是,一个dir命令显示这个文件的相对path存在:

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

Python是如何解释Windows上的相对path的? 什么是用相对path打开文件的正确方法?

另外 ,如果我在os.path.abspath()包装我的path,那么我得到这个输出:

 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' 

在这种情况下,似乎open()命令会自动转义\字符。

**令人尴尬的最终更新:看起来像我揉了一个字符在Windows中正确的方式来做这个Windows似乎是使用os.path.normpath() ,就像我原来的。

normpath只返回该特定路径的标准化版本。 它实际上并没有为你解决问题的工作。 你可能想要做os.path.abspath(yourpath)你的os.path.abspath(yourpath)

另外,我假设你在IronPython上。 否则,表示该字符串格式的标准方式是:

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

(对不起,这只是答复中途发布的问题,我对完整的解决方案感到困惑。