最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2018年08月29日 09:56:56   作者:adayabetter  
這篇文章主要介紹了Python實現(xiàn)查詢某個目錄下修改時間最新的文件,涉及Python使用os與shutil模塊針對文件的遍歷、屬性獲取、讀寫等相關操作技巧,需要的朋友可以參考下

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

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

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

直接擼代碼:

# -*- coding: utf-8 -*-
import os
import shutil
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)))
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): #如果是目錄,則遞歸執(zhí)行該方法
   listdir(file_path, list_name)
  else:
    list_name.append((file_path,os.path.getctime(file_path))) #把文件路徑,文件創(chuàng)建時間加入list中

def newestfile(target_list): #傳入包含文件路徑,文件創(chuàng)建時間的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入門與進階經典教程

希望本文所述對大家Python程序設計有所幫助。

相關文章

最新評論

江阴市| 潞西市| 喜德县| 株洲县| 海晏县| 凭祥市| 孟州市| 桑植县| 景泰县| 黑水县| 昭苏县| 中阳县| 香河县| 固安县| 汤原县| 揭西县| 嘉鱼县| 阳山县| 青岛市| 昭苏县| 廉江市| 文登市| 秦皇岛市| 苏州市| 铁岭市| 临洮县| 聂荣县| 凤翔县| 醴陵市| 镇赉县| 潼关县| 上饶县| 常山县| 太白县| 桦甸市| 自贡市| 翁牛特旗| 大渡口区| 金山区| 延安市| 平陆县|