我正在构建一个简单的助手脚本,用于将代码库中的两个模板文件复制到当前目录。但是,我没有存储模板的目录的绝对路径。我有一个相对路径从脚本,但当我调用脚本,它把它作为一个相对于当前工作目录的路径。是否有一种方法来指定这个相对url是来自脚本的位置?


当前回答

这是向系统路径集添加相对路径的简单方法。例如,对于目标目录比工作目录高一级(例如'/../')的常见情况:

import os
import sys
workingDir = os.getcwd()
targetDir = os.path.join(os.path.relpath(workingDir + '/../'),'target_directory')
sys.path.insert(0,targetDir)

对该解决方案进行了测试:

Python 3.9.6 |由conda-forge |打包(默认,2021年7月11日, 03:37:25) [MSC .1916 64位(AMD64)]

其他回答

正如在已接受的答案中提到的

import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir, '/relative/path/to/file/you/want')

我只是想补充一点

后一个字符串不能以反斜杠开头,实际上没有字符串 应该包含反斜杠吗

应该是这样的

import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir, 'relative','path','to','file','you','want')

接受的答案在某些情况下可能会误导,详情请参阅此链接

考虑一下我的代码:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

我不确定这是否适用于一些旧版本,但我相信Python 3.3具有原生相对路径支持。

例如,下面的代码应该在与python脚本相同的文件夹中创建一个文本文件:

open("text_file_name.txt", "w+t")

(注意,如果是相对路径,开头不应该有正斜杠或反斜杠)

一个简单的解决办法是

import os
os.chdir(os.path.dirname(__file__))

我认为要在所有系统中使用“ntpath”而不是“os.path”。如今,它在Windows、Linux和Mac OSX上都能很好地工作。

import ntpath
import os
dirname = ntpath.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')