zoukankan      html  css  js  c++  java
  • 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)


    结果如图:





  • 相关阅读:
    L-这是最难的题(二分+前缀和)
    SPFA 原理剖析代码实现分析比较
    树状数组---原理代码实现
    bellman-ford算法
    UML用例图总结
    UML类图几种关系的总结
    UML序列图总结
    线段树--Color the ball(多次染色问题)
    临时文档3
    POJ2676-Sudoku(数独)
  • 原文地址:https://www.cnblogs.com/tangjunjun/p/12152252.html
Copyright © 2011-2022 走看看