亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

通過(guò)Python腳本,查詢出某個(gè)目錄下修改時(shí)間最新的文件。

應(yīng)用場(chǎng)景舉例:比如有時(shí)候需要從ftp上拷貝自己剛剛上傳的文件,那么這時(shí)就需要判斷哪個(gè)文件的修改時(shí)間是最新的,即最后修改的文件是我們的目標(biāo)文件。

直接擼代碼:

# -*- coding: utf-8 -*-
import os
import shutil
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):
   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)

方法說(shuō)明:

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)的使用說(shuō)明

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中

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程

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

相關(guān)文章

最新評(píng)論