我的代码中有这个结构。
我需要从"data.ptk“打开文件"scrip.py",使用os.path可以提取脚本路径。
my_path = os.path.abspath(os.path.dirname(__file__))但是在结构上,我需要返回两个目录,然后输入"data“目录来打开文件。
简单的方法是用一个拆分(“/”)对字符串my_path进行分解,删除最后两个单词并添加"data“.但我不认为这是正确的方法
script.py需要独立于操作系统,这就是我无法“硬编码”放置de文件的目录的原因
有什么建议吗?谢谢。
发布于 2019-01-24 18:53:08
为了更详细地解释我的评论,您可以在这里看到pathlib的文档:https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib。它是python3的一个股票部分(不确定python2)。我认为以下几点是可行的:
from pathlib import Path
scriptPath = Path(__file__).absolute() # the absolute() is not strictly necessary
srcPath = scriptPath.parent
appPath = srcPath.parent
commonDirectory = appPath.parent # this could have been shortened with scriptPath.parent.parent.parent
dataPath = commonDirectory / 'data'
dtkFile = dataPath / 'data.ptk'https://stackoverflow.com/questions/54353419
复制相似问题