我正在构建一个简单的助手脚本,用于将代码库中的两个模板文件复制到当前目录。但是,我没有存储模板的目录的绝对路径。我有一个相对路径从脚本,但当我调用脚本,它把它作为一个相对于当前工作目录的路径。是否有一种方法来指定这个相对url是来自脚本的位置?
当前回答
考虑一下我的代码:
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)
其他回答
这段代码将返回主脚本的绝对路径。
import os
def whereAmI():
return os.path.dirname(os.path.realpath(__import__("__main__").__file__))
这甚至可以在一个模块中工作。
看到sys.path 在程序启动时初始化后,该列表的第一项路径[0]是包含用于调用Python解释器的脚本的目录。
使用此路径作为根文件夹,从中应用相对路径
>>> import sys
>>> import os.path
>>> sys.path[0]
'C:\\Python25\\Lib\\idlelib'
>>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
>>> os.path.join(sys.path[0], "path_to_libs")
'C:\\Python25\\Lib\\idlelib\\path_to_libs'
您需要os.path.realpath(下面的示例将父目录添加到您的路径中)
import sys,os
sys.path.append(os.path.realpath('..'))
以下是我的总结:
首先,定义名为relpath的工具函数,它将当前文件的相对路径转换为cwd的相对路径
import os
relpath = lambda p: os.path.normpath(os.path.join(os.path.dirname(__file__), p))
然后我们使用它来包装相对于当前文件的路径
path1 = relpath('../src/main.py')
你也可以调用sys.path.append()来导入相对于当前文件位置的文件
sys.path.append(relpath('..')) # so that you can import from upper dir
完整的示例代码:https://gist.github.com/luochen1990/9b1ffa30f5c4a721dab5991e040e3eb1
一个简单的解决办法是
import os
os.chdir(os.path.dirname(__file__))
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录