python3 os.path.realpath(__file__) 和 os.path.cwd() 方法的区别

来源:互联网 发布:软件汉化教程 编辑:程序博客网 时间:2024/06/04 08:50

os.path.realpath

获取当前执行脚本的绝对路径。

os.path.realpath(__file__)

os.path.cwd()

获取当前脚本的所在路径

脚本一:

所在路径:

/Users/wangxiansheng/Documents/Pycharm/PyMySQL/insert_sql.py

import osdef 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.pyinsert_sql cwd: /Users/wangxiansheng/Documents/Pycharm/PyMySQL

脚本二:

所在路径:

/Users/wangxiansheng/Documents/Pycharm/christian/cia.py

from PyMySQL import insert_sqlimport osinsert_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.pyinsert_sql cwd: /Users/wangxiansheng/Documents/Pycharm/christiancia cwd /Users/wangxiansheng/Documents/Pycharm/christiancia file: /Users/wangxiansheng/Documents/Pycharm/christian/cia.py

结论:
- realpath() 获得的是该方法所在的脚本的路径
- cwd,获得的是当前执行脚本的所在路径,无论从哪里调用的该方法。