【发布时间】:2010-09-24 01:24:57
【问题描述】:
我知道这是一个简单的、适合初学者的 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() 命令似乎自动转义了\ 字符。
**令人尴尬的最终更新:看起来我在 pathanme 中修改了一个字符 :) 在 Windows 上执行此操作的正确方法似乎是使用 os.path.normpath(),就像我最初所做的那样。
【问题讨论】:
-
什么行为?我们也需要输出。
-
我太早点击提交意外,问题现在已修复。