打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

文章目录

    • 1、sys.argv

    • 2、 _ _ file_ _

    • 3、sys.path

    • 4、os.getcwd()

    • 5、参考资料

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获取程序执行文件路径方法

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python sys模块的常见用法汇总
Python / 如何获得Python脚本所在目录的位置 | Elias的个人主页
我的Python笔记·模块化编程(三)
12.python内置模块之sys模块介绍
python之sys模块详解
python获取当前路径
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服