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:\pythontest\ostest下面最新的文件 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'