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 !

     

  • 相关阅读:
    抽象代数学习笔记
    WC2021 游记
    简单的数学题
    前缀和公式
    杜教筛
    [模板]BZOJ4756线段树合并
    SPOJ 694
    bzoj1367 可并堆
    莫比乌斯反演(理论)
    es6 Set数据结构
  • 原文地址:https://www.cnblogs.com/meloncodezhang/p/12013337.html
Copyright © 2011-2022 走看看