新建一个文件:testcode.py
import os
print(__file__) # __file__指代所在脚本的文件名
print(os.getcwd()) # 获取当前项目工作目录
print(os.path.realpath(__file__)) # 获取该方法所在脚本的绝对路径,包含文件名
print(os.path.dirname("/sata01/AIhome_ext/limin_ai/invoice_project/testcode.py")) #去掉文件名,返回目录
print(os.path.dirname(os.path.realpath(__file__))) # 获取的__file__所在脚本的路径,没有文件名
输出结果:
testcode.py
/sata01/AIhome_ext/liai/project
/sata01/AIhome_ext/liai/project/testcode.py
/sata01/AIhome_ext/liai/project
/sata01/AIhome_ext/liai/project
参考:
python3中 os.path.realpath(file) 的使用
python3 获取当前路径及os.path.dirname的使用