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

首頁 > 編程 > Python > 正文

Python實(shí)現(xiàn)查詢某個(gè)目錄下修改時(shí)間最新的文件示例

2020-01-04 14:37:41
字體:
供稿:網(wǎng)友

本文實(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_file
shutil.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是:

  • 1、可以是一個(gè)文件的名稱,則將source文件復(fù)制為新名稱的destination
  • 2、可以是一個(gè)文件夾,則將source文件復(fù)制到destination中
  • 3、若這個(gè)文件夾不存在,則將source目標(biāo)文件內(nèi)的內(nèi)容復(fù)制到destination中

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 新宾| 新乡县| 稻城县| 建德市| 逊克县| 自贡市| 定结县| 巴林右旗| 昆山市| 哈尔滨市| 高密市| 高阳县| 射阳县| 临武县| 大理市| 兴和县| 徐水县| 木里| 屏东县| 土默特右旗| 江口县| 阳江市| 五莲县| 邯郸市| 黄大仙区| 甘南县| 枞阳县| 农安县| 游戏| 肥东县| 同德县| 清丰县| 成安县| 吕梁市| 泰兴市| 莲花县| 鄂托克前旗| 西贡区| 噶尔县| 休宁县| 玛曲县|