os.path.realpath
获取当前执行脚本的绝对路径。
os.path.realpath(__file__)
os.path.cwd()
获取当前脚本的所在路径
脚本一:
所在路径:
/Users/wangxiansheng/Documents/Pycharm/PyMySQL/insert_sql.py
import os
def getpath():
file = os.path.realpath(__file__)
print('insert_sql file:', file)
cwd = os.getcwd()
print('insert_sql cwd:', cwd)
insert_sql file: /Users/wangxiansheng/Documents/Pycharm/PyMySQL/insert_sql.py
insert_sql cwd: /Users/wangxiansheng/Documents/Pycharm/PyMySQL
脚本二:
所在路径:
/Users/wangxiansheng/Documents/Pycharm/christian/cia.py
from PyMySQL import insert_sql
import os
insert_sql.getpath()
path = os.getcwd()
print('cia cwd', path)
file = os.path.realpath(__file__)
print('cia file:', file)
insert_sql file: /Users/wangxiansheng/Documents/Pycharm/PyMySQL/insert_sql.py
insert_sql cwd: /Users/wangxiansheng/Documents/Pycharm/christian
cia cwd /Users/wangxiansheng/Documents/Pycharm/christian
cia file: /Users/wangxiansheng/Documents/Pycharm/christian/cia.py
结论:
- realpath() 获得的是该方法所在的脚本的路径
- cwd,获得的是当前执行脚本的所在路径,无论从哪里调用的该方法。