zoukankan      html  css  js  c++  java
  • 路径path知识点

    1. 获取当前文件的路径

    test.py

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

    print(os.path.realpath(__file__)) # 返回path的真实路径
    结果:F:python高级知识点 est.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 !

     

  • 相关阅读:
    SVN cleanup操作反复失败解决办法
    mysql常用命令之-用户密码修改
    properties 配置文件中值换行的问题
    在每一行行尾添加内容
    Java 毫秒转换为日期类型、日期转换为毫秒
    SimpleDateFormat 12小时制以及24小时制的写法
    java校验时间格式 HH:MM
    ClassLoader 详解及用途(写的不错)
    ObjectInputStream类和ObjectInputStream类的使用
    logback 详解
  • 原文地址:https://www.cnblogs.com/meloncodezhang/p/12013337.html
Copyright © 2011-2022 走看看