国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現查詢某個目錄下修改時間最新的文件示例

2020-02-15 22:51:15
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現查詢某個目錄下修改時間最新的文件。分享給大家供大家參考,具體如下:

通過Python腳本,查詢出某個目錄下修改時間最新的文件。

應用場景舉例:比如有時候需要從ftp上拷貝自己剛剛上傳的文件,那么這時就需要判斷哪個文件的修改時間是最新的,即最后修改的文件是我們的目標文件。

直接擼代碼:

# -*- coding: utf-8 -*-import osimport shutildef listdir(path, list_name): #傳入存儲的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'))

運行結果:

('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): #傳入存儲的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))) #把文件路徑,文件創建時間加入list中
def newestfile(target_list): #傳入包含文件路徑,文件創建時間的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
shutil.copy(new_file[0], 'C://Users//Administrator//Desktop//img//a.xml') #文件拷貝

補充:shutil.copy(source, destination)的使用說明

shutil.copy(source, destination)(這種復制形式使用的前提是必須要有 os.chdir(你要處理的路徑)

source/destination 都是字符串形式的路勁,其中destination是:

1、可以是一個文件的名稱,則將source文件復制為新名稱的destination 2、可以是一個文件夾,則將source文件復制到destination中 3、若這個文件夾不存在,則將source目標文件內的內容復制到destination中

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 拜泉县| 舒兰市| 安义县| 常州市| 普安县| 长垣县| 石台县| 云和县| 错那县| 绥滨县| 闽侯县| 隆昌县| 同德县| 新乐市| 松溪县| 长阳| 且末县| 黄骅市| 侯马市| 互助| 健康| 镇宁| 明星| 佛坪县| 龙门县| 同江市| 东安县| 五华县| 文昌市| 凤山市| 阿鲁科尔沁旗| 黔西县| 家居| 凤翔县| 罗甸县| 岳阳市| 扎赉特旗| 玛曲县| 英山县| 乐都县| 沙雅县|