本文實(shí)例講述了Python實(shí)現(xiàn)查詢某個(gè)目錄下修改時(shí)間最新的文件。分享給大家供大家參考,具體如下:
通過Python腳本,查詢出某個(gè)目錄下修改時(shí)間最新的文件。
應(yīng)用場(chǎng)景舉例:比如有時(shí)候需要從ftp上拷貝自己剛剛上傳的文件,那么這時(shí)就需要判斷哪個(gè)文件的修改時(shí)間是最新的,即最后修改的文件是我們的目標(biāo)文件。
直接擼代碼:
# -*- coding: utf-8 -*-import osimport shutildef listdir(path, list_name): #傳入存儲(chǔ)的list for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append((file_path,os.path.getctime(file_path)))def newestfile(target_list): newest_file = target_list[0] for i in range(len(target_list)): if i < (len(target_list)-1) and newest_file[1] < target_list[i+1][1]: newest_file = target_list[i+1] else: continue print('newest file is',newest_file) return newest_file#p = r'C:/Users/WMB/700c-4'p = r'C:/Users/Administrator/Desktop/img'list = []listdir(p, list)new_file = newestfile(list)print('from:',new_file[0])print('to:',shutil.copy(new_file[0], 'C://Users//Administrator//Desktop//img//a.xml'))運(yùn)行結(jié)果:
('newest file is', ('C://Users//Administrator//Desktop//img//logo.gif', 1535508866.833419))
('from:', 'C://Users//Administrator//Desktop//img//logo.gif')
('to:', None)
方法說明:
def listdir(path, list_name): #傳入存儲(chǔ)的list for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): #如果是目錄,則遞歸執(zhí)行該方法 listdir(file_path, list_name) else: list_name.append((file_path,os.path.getctime(file_path))) #把文件路徑,文件創(chuàng)建時(shí)間加入list中
def newestfile(target_list): #傳入包含文件路徑,文件創(chuàng)建時(shí)間的list newest_file = target_list[0] #冒泡算法找出時(shí)間最大的 for i in range(len(target_list)): if i < (len(target_list)-1) and newest_file[1] < target_list[i+1][1]: newest_file = target_list[i+1] else: continue print('newest file is',newest_file) return newest_fileshutil.copy(new_file[0], 'C://Users//Administrator//Desktop//img//a.xml') #文件拷貝
補(bǔ)充:shutil.copy(source, destination)的使用說明
shutil.copy(source, destination)(這種復(fù)制形式使用的前提是必須要有 os.chdir(你要處理的路徑))
source/destination 都是字符串形式的路勁,其中destination是:
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選