python获取当前文件路径以及父文件路径的方法

yipeiwu_com6年前Python基础

#当前文件的路径
pwd = os.getcwd()
#当前文件的父路径
father_path=os.path.abspath(os.path.dirname(pwd)+os.path.sep+".")
#当前文件的前两级目录
grader_father=os.path.abspath(os.path.dirname(pwd)+os.path.sep+"..")

追加部分代码实例

def TestPrtPwd(self):
    print("获取当前文件路径——" + os.path.realpath(__file__)) # 获取当前文件路径
    parent = os.path.dirname(os.path.realpath(__file__))
    print("获取其父目录——" + parent) # 从当前文件路径中获取目录
    garder = os.path.dirname(parent)
    print("获取父目录的父目录——" + garder)
    print("获取文件名" + os.path.basename(os.path.realpath(__file__))) # 获取文件名
    # 当前文件的路径
    pwd = os.getcwd()
    print("当前运行文件路径" + pwd)
    # 当前文件的父路径
    father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")
    print("运行文件父路径" + father_path)
    # 当前文件的前两级目录
    grader_father = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..")
    print("运行文件父路径的父路径" + grader_father)
    return garder

运行结果:

获取当前文件路径——D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData\common\redConfig.py
获取其父目录——D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData\common
获取父目录的父目录——D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData
获取文件名redConfig.py
当前运行文件路径D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData\TestSuite\RoleManagement
运行文件父路径D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData\TestSuite
运行文件父路径的父路径D:\SVN\测试\autotest\functionalAutomation\aonr_sxsj\AuditData

以上这篇python获取当前文件路径以及父文件路径的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python定时器实例代码

在实际应用中,我们经常需要使用定时器去触发一些事件。Python中通过线程实现定时器timer,其使用非常简单。看示例: import threading def fun_timer...

利用pyshp包给shapefile文件添加字段的实例

在已有的shapefile文件的基础上增加字段: # -*- coding:gb2312 -*- import shapefile r=shapefile.Reader(r"C:...

Python判断字符串与大小写转换

判断字符串 s.isalnum() #所有字符都是数字或者字母 s.isalpha() #所有字符都是字母 s.isdigit() #所有字符都是数字 s.islower() #所有...

python单线程实现多个定时器示例

单线程实现多个定时器 NewTimer.py复制代码 代码如下:#!/usr/bin/env python from heapq import *from threading impor...

Pytorch GPU显存充足却显示out of memory的解决方式

今天在测试一个pytorch代码的时候显示显存不足,但是这个网络框架明明很简单,用CPU跑起来都没有问题,GPU却一直提示out of memory. 在网上找了很多方法都行不通,最后我...