zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    MianShiTi
    C#多线程解决界面卡死问题的完美解决方案
    C#中的WebBrowser控件的使用
    解决Linq第一次调用存储过程时速度慢的问题
    AX 的 NumberSequences
    Ax 从一个form关闭另外一个form,AX全局变量
    查询数据库后台Block 的Sql存储过程
    Dynamic AX 4.0 用户组权限SecurityKey
    20160408 从软件工程的3大文档开始说起
    获取AX的窗口所有控件的lableID及内容
  • 原文地址:https://www.cnblogs.com/yejifeng/p/11428918.html
Copyright © 2011-2022 走看看