如何拆分从os.path.dirname()收到的路径

时间:2017-07-19 12:57:31

标签: python

假设我在目录

中保存了一个python文件
E:\Data\App

所以,当我print os.path.dirname(str(sys.argv[0]))时,它向我展示了上述路径。现在假设我想在E:\Data\Conf\内创建一个新文件,那么如何删除App并使用Conf并将文件保存在E:\Data\Conf

我无法直接使用完整路径,因为E:\Data\不常见且会有所不同。

感谢。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

path = 'E:\Data\conf' # Or however you will assign this
dir_path = '\\'.join(path.split('\\')[:-1]) + '\\' # 'E:\Data\'

这基本上将路径的字符串拆分为\,然后使用树中的最后一个路径重建字符串。

答案 1 :(得分:0)

from os.path import dirname, join

file_dir = dirname(the_file)
parent_dir = dirname(file_dir)
conf_dir = join(parent_dir, 'Conf')

dirname总是得到包含你传递它的路径的目录,所以在你的文件中调用它会得到app目录;在app目录中再次调用它将获得它的父级。然后,您可以使用os.path.join附加"Conf"或您想要的任何其他目录。

另一种方法是使用os.path.abspathos.pardir上升任意数量的级别:

import os
from os.path import abspath, dirname, join

conf_dir = abspath(join(dirname(the_file), os.pardir, "Conf"))
                                         # ^ You can add more of these to go up the heirarchy

join进行内部os.pardir调用将构建类似"E:\Data\App\..\Conf"的路径,abspath会将其解析为"E:\Data\Conf"