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)

 

转载于:https://www.cnblogs.com/liuguanghai6455/p/10625417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值