使用Python获取当前路径时,有多种方法可选择,例如:
print('sys.argv[0]', sys.argv[0])
print('__file__', __file__)
print('os.getcwd()', os.getcwd())
print('os.path.abspath(\'.\')', os.path.abspath('.'))
假设我们这样执行:
python.exe f:/Workspace/test/Paths/test.py
输出的结果是:
sys.argv[0] f:/Workspace/test/Paths/test.py
__file__ f:/Workspace/test/Paths/test.py
os.getcwd() F:\Workspace\test\Paths
os.path.abspath('.') F:\Workspace\test\Paths
如果我们添加些目录层次,再做测试,假设目录结构如下:
│ test.py
│
└──a
│ testa.py
│ __init__.py
│
└─a1
│ testa1.py
└─__init__.py
testa.py和testa1.py的内容类似:
import sys, os
def pintPath():
file = 'a.testa.py'
print(file, 'sys.argv[0]', sys.argv[0])
print(file, '__file__', __file__)
print(file, 'os.getcwd()', os.getcwd())
print(file, 'os.path.abspath(\'.\')', os.path.abspath('.'))
最外层的test.py分别调用每个pintPath(),执行的结果是:
a.testa.py sys.argv[0] f:/Workspace/test/Paths/test.py
a.testa.py __file__ f:\Workspace\test\Paths\a\testa.py
a.testa.py os.getcwd() F:\Workspace\test\Paths
a.testa.py os.path.abspath('.') F:\Workspace\test\Paths
a.a1.testb.py sys.argv[0] f:/Workspace/test/Paths/test.py
a.a1.testb.py __file__ f:\Workspace\test\Paths\a\a1\testa1.py
a.a1.testb.py os.getcwd() F:\Workspace\test\Paths
a.a1.testb.py os.path.abspath('.') F:\Workspace\test\Paths
由测试看到,sys.argv[0]、os.getcwd()和os.path.abspath('.')的值不会随目录层级的变化而改变;__file__是.py文件的路径名称。
但是要注意,sys.argv[0]并不一直是你期待的内容,官方文档对sys.argv的说明是:
一个列表,其中包含了被传递给 Python 脚本的命令行参数。 argv[0]
为脚本的名称(是否是完整的路径名取决于操作系统)。如果是通过 Python 解释器的命令行参数 -c
来执行的, argv[0]
会被设置成字符串 '-c'
。如果没有脚本名被传递给 Python 解释器, argv[0]
为空字符串。
https://docs.python.org/zh-cn/3.7/library/sys.html#sys.argv
所以,如果想获取当前工作目录,还是应该使用os.getcwd()会保险些。