zoukankan      html  css  js  c++  java
  • Python 内置os模块的简单实用

     获取路径&目录添加文件

    在自动化测试的过程,考虑到工程文件的移动或者在其他人的工作环境中运行,所以我们的路径要灵活,不能把路径写死。

    推荐使用Python的内置模块OS

    参照图

    import unittest
    from common.HTMLTestRunner_cn import HTMLTestRunner
    import os
    # 当前脚本路径
    curPath = os.path.realpath(__file__)
    print(curPath)
    # 当前脚本文件夹名称
    proPath = os.path.dirname(curPath)
    print(proPath)
    #测试用例的路径
    startCase = os.path.join(proPath, "test_case")
    print(startCase)
    # 测试报告的路径
    reportPath = os.path.join(proPath, "report", "report.html")
    print(reportPath)

     路径的操作

    #获取当前目录
    print(os.getcwd())
    print(os.path.abspath(os.path.dirname(__file__)))
    #获取上级目录
    print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
    print(os.path.abspath(os.path.dirname(os.getcwd())))
    print(os.path.abspath(os.path.join(os.getcwd(), "..")))
    #获取上上级目录
    print(os.path.abspath(os.path.join(os.getcwd(), "../..")))

    获取最新文件

    测试过程中我们会多次执行生成多次的测试报告,那么如何获取最新的测试报告呢?

    案例图:

    如图,report下有许多的测试报告

    import os
    # 当前脚本文件夹名称
    proPath = os.path.dirname( os.path.realpath(__file__))
    print(proPath)
    
    def get_newest_report(report_path):
        #列举report_path目录下的所有文件(名),结果以列表形式返回
        lists =os.listdir(report_path)
        # sort按key的关键字进行升序排序,lambda的入参fn为lists列表的元素,获取文件的最后修改时间,所以最终以文件时间从小到大排序
        # 最后对lists元素,按文件修改时间大小从小到大排序。
        # 获取最新文件的绝对路径,列表中最后一个值,文件夹+文件名
        #lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))  #两种方法排序
        lists.sort(key=lambda fn: os.path.getmtime(report_path+"\"+fn))             #两种方法排序
        print(u'最新测试生成的报告: '+lists[-1])
        report_file = os.path.join(report_path, lists[-1])
        return report_file
    
    if __name__ == "__main__":
        report_path = os.path.join(proPath, "report")  #报告所在目录(report_path)
        report_file = get_newest_report(report_path)   #返回report_path下最新的文件

    os.path.getmtime与os.path.getctime的区别:

    import os
    import time
    file = 'C:\UsersAdministratorPycharmProjects\unittest_lianxi'
    print(os.path.getatime(file))# 输出最近访问时间
    print(os.path.getctime(file))# 输出文件创建时间
    print(os.path.getmtime(file))# 输出最近修改时间
    print(time.gmtime(os.path.getmtime(file)))# 以struct_time形式输出最近修改时间
    print(os.path.getsize(file)) # 输出文件大小(字节为单位)
    print(os.path.abspath(file)) # 输出绝对路径
    print(os.path.normpath(file) )
  • 相关阅读:
    Maven的settings.xml配置详解
    Activiti创建表(三)
    解决报错:The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized
    解决报错(Could not create connection to database server.)
    Activiti插件安装(二)
    2018年四川理工学院软件工程考试大纲(软件工程概述)
    通过myclipse建立一个简单的Hibernate项目(PS:在单元测试中实现数据的向表的插入)
    MySQL如何永久解决由dos编码格式导致MySQ的显示乱码
    nyoj 209 + poj 2492 A Bug's Life (并查集)
    nyoj 208 + poj 1456 Supermarket (贪心)
  • 原文地址:https://www.cnblogs.com/fanjc/p/9922220.html
Copyright © 2011-2022 走看看