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函數也叫匿名函數,即,函數沒有具體的名稱。html
key=lambda fn:os.path.getmtime(test_dir+'\\'+fn) #至關於 def key(fn): return os.path.getmtime(test_dir+'\\'+fn)
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模塊下經常使用的用法總結》python