python下获取文件所在的目录

249 阅读1分钟
import os
print("os.path.realpath(__file__)=%s" % os.path.realpath(__file__))  # __file__是当前执行的文件
print("os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(
    os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__))=%s" % os.path.split(
    os.path.realpath(__file__))[0])


# 输出
os.path.realpath(__file__)=/Users/xxx/test/python_lib_test/test/class_test.py
os.path.dirname(os.path.realpath(__file__))=/Users/xxx/test/python_lib_test/test
os.path.split(os.path.realpath(__file__))=/Users/xxx/test/python_lib_test/test