• 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") 
    
    
    
    
    """ 路径的拼接 """
    #路径中最好使用双斜杆 \
    import os
    path1 = "E:\PythonWorkSpace"  
    path2 = "test.txt"
    path = os.path.join(path1, path2)
    print(path)
    
    
    
    """ 遍历目录下所有文件 """
    rootdir = 'F:data'
    list = os.listdir(rootdir)
    for e in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isfile(path):
                pass
    
  • 相关阅读:
    Js计算时间差(天、小时、分钟、秒)
    [原创]chromium源码阅读-进程间通信IPC.消息的接收与应答
    loki之内存池SmallObj[原创]
    A Cross-Platform Memory Leak Detector
    UML Diagrams Using Graphviz Dot
    My Emacs Writing Setup
    Drawing Graphs using Dot and Graphviz
    SHFileOperation的用法
    latex中文模板
    C++ Design Pattern: What is a Design Pattern?
  • 原文地址:https://www.cnblogs.com/yejifeng/p/11428918.html
Copyright © 2020-2023  润新知