python 获取当前,上级,上上级路径(任何上级路径)

我看了一些博客,对获得当前路径有很多方法,如os.getcwd()与os.path.abspath(r"."),其中os.path.abspath(r"..")可以得到上一层路径,

然而,有些麻烦,我将利用split与当前路径获取方法,写出函数,可以获得任何上一层绝对路径。该函数有一个参数,用于调节你想获得路径

层次,其含义已在下面代码中说明,详细看其代码。

import os
def get_path(path_int):
'''
:param path_int: 0表示获取当前路径,1表示当前路径的上一次路径,2表示当前路径的上2次路径,以此类推
:return: 返回我们需要的绝对路径,是双斜号的绝对路径
'''
path_count=path_int
path_current=os.path.abspath(r".")
# print('path_current=',path_current)
path_current_split=path_current.split('\\')
# print('path_current_split=',path_current_split)
path_want=path_current_split[0]
for i in range(len(path_current_split)-1-path_count):
j=i+1
path_want=path_want+'\\\\'+path_current_split[j]
return path_want

import cv2 as cv
if __name__=='__main__':

a=get_path(0) # 得到当前路径
print('当前路径',a)
a=get_path(1) # 得到上一层路径
print('上一层路径',a)


结果如图:





猜你喜欢

转载自www.cnblogs.com/tangjunjun/p/12152252.html