1. 获得该文件的绝对路径
os.path.abspath(__file__)
2. 获得该文件所在的真实全部路径
os.path.realpath(__file__)
3. 获得该文件所在的文件夹路径
os.path.split(os.path.realpath(__file__))[0]

示例

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())
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')

参考文章:

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐