python2.7遍歷文件夾下所有目錄,顯示文件時間和文件修改時間與當前的時間差


1 說明

工作學習中經常會用到需要遍歷某個文件夾目錄下的文件,可能的需求如下:

  • 顯示文件最后修改的時間
  • 比較文件最后修改時間和當前的時間差,當超過一定的時間文件未更新需要刪除或者備份等操作

 

2 代碼

 

# -*- coding: utf-8 -*-
import os
import sys
import time

reload(sys)
sys.setdefaultencoding('utf8')

path = u"/home"
def check_file_time(path, time_flag):
    for root, dir, files in os.walk(path):
        for file in files:
            try:
                full_path = os.path.join(root, file)
                mtime = os.stat(full_path).st_mtime
            except IOError:
                continue
            ctime=time.time()
            print("time is: %d"% (ctime-mtime))
            if ctime- mtime > time_flag:
                file_modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime))
                print("{0} [file modify time]: {1}".format(full_path,file_modify_time))

if __name__=="__main__":
    count=0
    while True:
        check_file_time(path, 300)
        count+=1
        print("loop times: %d" % count)
        print("")
        time.sleep(2)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM