# -*- coding: utf-8 -*-
from termcolor import colored
import sys
print(colored('sys.path=','cyan'))
print(sys.path)

import os
print()

print(colored('__file__=','cyan'))
print(__file__)

print()
print(colored('os.path.dirname(__file__)=','cyan'))
print(os.path.dirname(__file__))

print()
print(colored('os.path.realpath(__file__)=','cyan'))
print(os.path.realpath(__file__))

print()
print(colored("os.paht.join(os.path.dirname(__file__),'..'=",'cyan'))
print(os.path.join(os.path.dirname(__file__), '..'))

print()
print(colored('os.path.dirname(os.path.realpath(__file__)=','cyan'))
print(os.path.dirname(os.path.realpath(__file__)))

print()
print(colored('os.path.abspath(os.path.dirname(__file__)=','cyan'))
print(os.path.abspath(os.path.dirname(__file__)))

直接在spyder IDE中按运行键运行

输出:

从例子看python __file___相对路径

sys.path=
['/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '', '/home/dell/workenv/lib/python3.6/site-packages', '/home/dell/myprojects/pybullet/src/rllib/gym-pybullet', '/home/dell/workenv/lib/python3.6/site-packages/IPython/extensions', '/home/dell/myprojects/pybullet/src/rllib', '/home/dell/.ipython']

__file__=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.paht.join(os.path.dirname(__file__),'..'=
/home/dell/myprojects/pybullet/src/rllib/..

os.path.dirname(os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.abspath(os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib

分析:

  1. 我当前的解释器是virtualenv环境下的python3.6,而这个解释器在sys.path路径中
  2. file输出的就是这个python文件自己的路径
  3. dirname输出的是python文件所在的文件夹名称
  4. realpath就是文件的绝对路径,和file是相同的

而我们看下一种情况,同样的代码输出会有所不同

在终端中通过 python test_file.py执行

输出:

从例子看python __file_____file___02

sys.path=
['/home/dell/myprojects/pybullet/src/rllib', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/dell/workenv/lib/python3.6/site-packages', '/home/dell/myprojects/pybullet/src/rllib/gym-pybullet']

__file__=
test_file.py

os.path.dirname(__file__)=


os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib/test_file.py

os.paht.join(os.path.dirname(__file__),'..'=
..

os.path.dirname(os.path.realpath(__file__)=
/home/dell/myprojects/pybullet/src/rllib

os.path.abspath(os.path.dirname(__file__)=
/home/dell/myprojects/pybullet/src/rllib

情况就有所不同
分析:

  1. file就只显示自己的文件名称
  2. dirname(file)不显示任何东西
  3. join显示的是相对路径
  4. 所以,这样执行方式输出的都是相对路径
  5. 因为当前解释器在sys.path中,所以才以相对路径的方式工作
  6. 至于为什么在IDE中是以绝对路径的方式,我也不知道,谁能告诉我一下

再来看一个例子

import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)