2008-11-25 97 views
3

我知道这是一个简单的初学者Python问题,但我在使用相对路径打开文件时遇到问题。这种行为似乎很奇怪,我(从非Python的背景的):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命令显示在相对路径此文件存在:

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

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

此外,如果我换在os.path.abspath()我的道路,然后我得到这样的输出:

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(),正如我原来的。

+0

的行为什么?我们也需要输出。 – Patrick 2008-11-25 21:59:16

+0

我太早提交了意外,问题现在已修复。 – 2008-11-25 22:02:07

回答

3

normpath只返回该特定路径的标准化版本。它实际上并不为解决的工作路径。你可能想要做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)) 

(对不起,这只是一个问题的一半贴出的问题我很疑惑的完全解决方案)