码迷,mamicode.com
首页 > 其他好文 > 详细

路径path知识点

时间:2019-12-09 21:32:21      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:技术   xixi   height   需求   etc   路径   port   高级   http   

技术图片

1. 获取当前文件的路径

test.py

os.path.abspath(path)  # 返回当前文件运行的绝对路径

print("程序的绝对路径是",os.path.abspath(__file__)) # __file__就是当这个文件的绝对路径,
结果:程序的绝对路径是 F:\python高级知识点\test.py

print("程序当前的路径是",os.getcwd())
结果:程序当前的路径是 F:\python高级知识点

print(__file__) # 
结果:F:/python高级知识点/test.py

print(os.path.realpath(__file__)) # 返回path的真实路径
结果:F:\python高级知识点\test.py

print(os.path.split(os.path.realpath(__file__))) # 一般通过元组[0] 获取路径 F:\\python高级知识点
结果:(‘F:\\python高级知识点‘, ‘test.py‘)

print(os.path.split(os.path.realpath(__file__)))[0]

结果:F:\python高级知识点

 2. demo.py 

需求,在demo.py中读取test.txt里面的内容

import os
print("当前文件所在文件夹的路径是",os.path.dirname(__file__)) # 返回当前文件所在文件夹的路径
结果:当前文件所在文件夹的路径是 F:/python高级知识点/demo
print("当前文件的父级文件夹的路径是",os.path.dirname(os.path.dirname(__file__)))
结果:当前文件的父级文件夹的路径是 F:/python高级知识点

rootpath = os.path.dirname(os.path.dirname(__file__))

with open(rootpath+"/test.txt","r") as f:
    ret = f.read()
    print(ret)

结果:this is a test !

 

3. xixi.py

需求:在xixi.py中读取,test.txt里面的内容
import os
root_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
with open(root_path + /test.txt,r) as f:
    ret = f.read()
    print(ret)

结果: this is a test !

 

 

 

 

 

 

 

 

 

 

 

 

 

 

路径path知识点

标签:技术   xixi   height   需求   etc   路径   port   高级   http   

原文地址:https://www.cnblogs.com/meloncodezhang/p/12013337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!