【Selenium + Python】之如何获取最新的报告以及os.path.getmtime与os.path.getctime的区别

import os
def new_file(test_dir):
    #列举test_dir目录下的所有文件(名),结果以列表形式返回。
    lists=os.listdir(test_dir)
    #sort按key的关键字进行升序排序,lambda的入参fn为lists列表的元素,获取文件的最后修改时间,所以最终以文件时间从小到大排序
    #最后对lists元素,按文件修改时间大小从小到大排序。
    #获取最新文件的绝对路径,列表中最后一个值,文件夹+文件名
    lists.sort(key=lambda fn:os.path.getmtime(test_dir+'\'+fn)) 
    file_path=os.path.join(test_dir,lists[-1])
    return file_path

#返回D:pythontestostest下面最新的文件
print new_file('D:\system files\workspace\selenium\email126pro\email126\report')

最后再啰嗦一句,关于lambda的用法(python中单行的最小函数):

lambda函数也叫匿名函数,即,函数没有具体的名称。

key=lambda fn:os.path.getmtime(test_dir+'\'+fn)
#相当于
def key(fn):
    return os.path.getmtime(test_dir+'\'+fn)

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

import os
import time
file='/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'
os.path.getatime(file)   #输出最近访问时间1318921018.0
os.path.getctime(file)   #windows环境下是输出文件创建时间;如果是linux环境下ctime代表“状态时间”
os.path.getmtime(file)   #输出最近修改时间
time.gmtime(os.path.getmtime(file))   #以struct_time形式输出最近修改时间
os.path.getsize(file)    #输出文件大小(字节为单位)
os.path.abspath(file)    #输出绝对路径'/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'
os.path.normpath(file)   #输出'/Volumes/Leopard/Users/Caroline/Desktop/1.mp4'

附录:

python3中,os.path模块下常用的用法总结

原文地址:https://www.cnblogs.com/Owen-ET/p/8610446.html