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)