Python获取当前执行文件,根据某一级目录名称,获取此目录名称所在的绝对路径

时间:2022-11-02 18:43:42

假如当前文件绝对路径:E:\learn\python\我的file\my.py

#coding:utf-8
import os

#dirName:上级目录名称
#sysCoding:系统编码格式
#targetCoding:转换目标编码格式
def get_dir_realpath(dirName,sysCoding,targetCoding):
    path = os.path.split(os.path.realpath(__file__))[0].decode(sysCoding).encode(targetCoding)
    dirList = path.split("\\")
    length = len(dirList)
    for _ in range(1,length):
        fileName = os.path.split(path)[1]
        path = os.path.split(path)[0]
        if fileName == dirName:
            return path
            break
    return ""
        
print get_dir_realpath("我的file",'cp936',"utf-8") 执行结果:E:\learn\python
print get_dir_realpath("python",'cp936',"utf-8") 执行结果:E:\learn