python获取路径的方法_Python获取脚本路径的几种方法讨论

获取脚本路径有好多方法。如下列出几种方法并讨论几种方法的异同。

通过os.getcwd()获取

通过sys.path[0]获取

通过os.path.split(os.path.realpath(__file__))[0]获取

通过 os.getcwd 获取

这种方式获取的路径是当前的工作目录。也就是在命令行起脚本(该脚本不一定是写有os.getcwd的脚本)的路径。

通过 sys.path[0] 获取

这种方式获取的路径是初始执行的脚本的目录。

通过 os.path.split(os.path.realpath(file))[0] 获取

这种方式获取的路径是该脚本的路径。

例子

层级结构:

/base_dir/

-|path_tst

-|super_path.py

-|model

-|mod_path.py

mod_path.py的代码如下:

import os

import sys

def get_cwd_m():

return os.getcwd()

def sys_path_m():

return sys.path[0]

def file_path_m():

return os.path.split(os.path.realpath(__file__))[0]

super_path.py的代码如下:

from model.mod_path import get_cwd_m

from model.mod_path import sys_path_m

from model.mod_path import file_path_m

if __name__ == "__main__":

cwd_pth = get_cwd_m()

sys_pth = sys_path_m()

file_pth = file_path_m()

print("cwd_path: {}".format(cwd_pth))

print("sys_path: {}".format(sys_pth))

print("file_path: {}".format(file_pth))

现在在/base_dir/ 目录下执行 python3 path_tst/super_path.py。执行结果如下:

cwd_path: /base_dir/

sys_path: /base_dir/path_tst

file_path: /base_dir/path_tst/model

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值