一. Python 获取当前文件路径方法
1. os.getcwd()
获取文件当前工作目录路径(绝对路径)https://docs.python.org/2/library/os.html#os.getcwd
2. sys.path[0]
获取文件当前工作目录路径(绝对路径)
sys.argv[0]|获得模块所在的路径(由系统决定是否是全名)
若显示调用python指令,如python demo.py,会得到绝对路径;
若直接执行脚本,如./demo.py,会得到相对路径。
3. __ file __
获得文件所在的路径(由系统决定是否是全名)
若显示执行Python,会得到绝对路径;
若按相对路径来直接执行脚本./pyws/path_demo.py,会得到相对路径。
4. os.path.abspath(__ file __)
获得文件所在的路径(绝对路径)
5. os.path.realpath(__ file __)
获得文件所在的路径(绝对路径)https://docs.python.org/2/library/os.path.html#os.path.realpath
6. os.path.split(os.path.realpath(__ file __))
将文件路径名称分成头和尾一对,生成二元元组。(文件目录,文件名)
https://docs.python.org/2/library/os.path.html#os.path.split
二. 举个栗子
1. Source code
import os
import sys
print("sys.path[0] = ", sys.path[0])
print("sys.argv[0] = ", sys.argv[0])
print("__file__ = ", __file__)
print("os.path.abspath(__file__) = ", os.path.abspath(__file__))
print("os.path.realpath(__file__) = ", os.path.realpath(__file__))
print("os.path.dirname(os.path.realpath(__file__)) = ",
os.path.dirname(os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__)) = ",
os.path.split(os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__))[0] = ",
os.path.split(os.path.realpath(__file__))[0])
print("os.getcwd() = ", os.getcwd())
2. Result
(1) Pycharm project中显示调用python指令,获取文件绝对路径
C:\Python364\python.exe C:/PyCharm/PycharmProject/get_path/path_demo.py
sys.path[0] = C:\PyCharm\PycharmProject\get_path
sys.argv[0] = C:/PyCharm/PycharmProject/get_path/path_demo.py
__file__ = C:/PyCharm/PycharmProject/get_path/path_demo.py
os.path.abspath(__file__) = C:\PyCharm\PycharmProject\get_path\path_demo.py
os.path.realpath(__file__) = C:\PyCharm\PycharmProject\get_path\path_demo.py
os.path.dirname(os.path.realpath(__file__)) = C:\PyCharm\PycharmProject\get_path
os.path.split(os.path.realpath(__file__)) = ('C:\\PyCharm\\PycharmProject\\get_path', 'path_demo.py')
os.path.split(os.path.realpath(__file__))[0] = C:\PyCharm\PycharmProject\get_path
os.getcwd() = C:\PyCharm\PycharmProject\get_path
Process finished with exit code 0
(2)Terminal中直接执行Python脚本,获取文件相对路径
C:\PyCharm\PycharmProject\get_path>python path_demo.py
('sys.path[0] = ', 'C:\\PyCharm\\PycharmProject\\get_path')
('sys.argv[0] = ', 'path_demo.py')
('__file__ = ', 'path_demo.py')
('os.path.abspath(__file__) = ', 'C:\\PyCharm\\PycharmProject\\get_path\\path_demo.py')
('os.path.realpath(__file__) = ', 'C:\\PyCharm\\PycharmProject\\get_path\\path_demo.py')
('os.path.dirname(os.path.realpath(__file__)) = ', 'C:\\PyCharm\\PycharmProject\\get_path')
('os.path.split(os.path.realpath(__file__)) = ', ('C:\\PyCharm\\PycharmProject\\get_path', 'path_demo.py'))
('os.path.split(os.path.realpath(__file__))[0] = ', 'C:\\PyCharm\\PycharmProject\\get_path')
('os.getcwd() = ', 'C:\\PyCharm\\PycharmProject\\get_path')
三. 参考
1. http://rustfisher.github.io/2017/07/31/Python_note/Python-get-path/