我知道这是一个简单的、初学者的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
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
titlesFile = open(titles_path, 'r')
IOError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\Downloads\\downloads\\movie_titles.txt'
在这种情况下,似乎open()命令正在自动转义\字符。
**令人尴尬的最终更新:看起来我在路径中咀嚼了一个字符:)在Windows上执行此操作的正确方法似乎是使用os.path.normpath(),正如我最初所做的那样。