Python中的相对路径问题

2024-05-05 16:17:50 发布

您现在位置: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上执行此操作的正确方法似乎是使用os.path.normpath(),正如我最初所做的那样。


Tags: pathtxtisosdownloadsexistsmattopen
1条回答
网友
1楼 · 发布于 2024-05-05 16:17:50

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))

(对不起,这只是半个问题的答案。我对完整的解决方案感到困惑。)

相关问题 更多 >