编程语言
首页 > 编程语言> > python的路径问题

python的路径问题

作者:互联网

## 文件路径出错问题

""" 如何获取与当前文件相关的地址 """
import os

# 当前文件的完整路径
print(__file__) #__file__表示了当前文件的路径
print(os.path.abspath(__file__))  #os.path.abspath功能返回一个目录的绝对路径
print(os.path.realpath(__file__)) #os.path.realpath功能返回指定文件的标准路径,而非软链接所在的路径
# 两者的差别是,当你用相对路径运行该文件时候,__file__的值是该相对路径
# 所以推荐使用 os.path.abspath 和os.path.realpath,确保值为绝对路径


# 当前文件所处的文件夹的绝对路径
print(os.path.dirname(os.path.abspath(__file__)))  #os.path.dirname(path)功能是去掉文件名,返回目录
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.split(__file__)[0]))


# 当前文件所处的文件夹的上一级文件夹的绝对路径
print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(os.path.abspath(os.path.split(os.path.split(__file__)[0])[0]))



# 当前运行空间的绝对路径
print(os.path.abspath('.'))



# 当前运行空间的上一级文件夹的绝对路径
print(os.path.abspath('..'))





""" 如何引入自己编写的模块 """
import os,sys
sys.path.append(os.path.dirname(os.path.abspath(__file__))) #将当前文件所处的文件夹的绝对路径导入搜索路径
from tool import Tool
print(Tool.sum(1,1))





""" 使用绝对路径导入图片,文本等资源 """
#当文本和本文件在同一文件夹下可以这么写
os.path.join(os.path.dirname(os.path.abspath(__file__)), "a.txt") 

标签:__,python,abspath,路径,问题,file,print,path,os
来源: https://www.cnblogs.com/yejifeng/p/11428918.html