python获取文件当前路径方法汇总

1、sys.argv

sys.argv保存的是脚本的指令参数列表,sys.argv[0]是“执行”脚本的名字。print(sys.argv[0])返回相对路径还是绝对路径,主要看你脚本的执行方式,如下:

#当前路径
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd
/Users/schillerxu/Documents/sourcecode/python/numpy_test
#代码
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ cat 3.py
import sys
import os
print(sys.argv)
print(sys.argv[0])
#两种不同的执行方法对比
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py
['3.py']
3.py
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
['/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py']
/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py

如果获取的是相对路径,可以用os.path.abspath(sys.argv[0])得到绝对路径,用os.path.split()可以得到目录名和文件名,代码如下:

import sys
import os
path=sys.argv[0]
abs_path=os.path.abspath(sys.argv[0])
dirname,filename=os.path.split(abs_path)
print(path)
print(abs_path)
print(dirname,filename)

程序运行的结果如下:

(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd
/Users/schillerxu/Documents/sourcecode/python/numpy_test
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py
3.py
/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
/Users/schillerxu/Documents/sourcecode/python/numpy_test 3.py

最后获得目录名和文件名。

2、 _ _ file_ _

__ file__是当前脚本的名字,如果在当前脚本使用, __ file__和sys.argv[0]效果是一样的,比如代码如下:

import sys
import os
print(__file__)

运行结果:

(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py 
3.py
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py

同样受到脚本执行参数的影响。

但是如果脚本互相引用,__ file__和sys.argv[0]结果略有不同,比如代码:

a.py

import sys
def f():
    print(sys.argv[0])
    print(__file__)

3.py

import sys
import os
import a

print(sys.argv[0])
print(__file__)

a.f()

执行结果:
在这里插入图片描述

可以看到__file__返回的是被调用(当前)的文件,sys.argv[0]更多的是脚本执行的参数。

3、sys.path

sys.path保存了python解释器的部分路径,可以自己试下,其中sys.path[0]是执行脚本所在的目录。
代码:

import sys
import os

print(sys.path[0])

结果:

$ python 3.py
/Users/schillerxu/Documents/sourcecode/python/numpy_test

4、os.getcwd()

os.getcwd()返回的是工作目录,并不一定是脚本所在目录。

代码:

import sys
import os

print(os.getcwd())

运行结果:
在这里插入图片描述

5、参考资料

python获取程序执行文件路径方法

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值