首页 > 技术文章 > Python清理过期文件

delav 2018-11-09 17:25 原文

改程序执行后,会清理 test/文件夹中距离现在超过一天的以 .xml 结尾的文件

# coding: utf-8

import time
import os
root = os.path.dirname(__file__)
def clear_file(root_dir):
    print(333333)
    for root, dir, names in os.walk(root_dir):
        print(root, dir, names)
        for name in names:
            filename = os.path.join(root, name)
            ct = os.stat(filename).st_ctime
            nt = time.time()
            s1 = time.localtime(ct)
            s2 = time.localtime(nt)
            print "s%文件创建时间为%s", (name, time.strftime('%Y-%m-%d', s1))
            print "当前时间为:", time.strftime('%Y-%m-%d', s2)

            tt = nt - ct
            m, s = divmod(tt, 60)
            h, m = divmod(m, 60)
            d, h = divmod(h, 24)
            print "文件创建距离现在已%02d天%02d时%02d分%02d秒" % (d, h, m, s)
            if d >= 1 and name.endswith('.xml'):
                print "文件超过一天,执行清理"
                os.remove(filename)
            elif d < 1 and m < 10 and name.endswith('.xml'):
                os.remove(filename)

if __name__ == '__main__':
  root = root+'/test/'
  clear_file(root)

 

推荐阅读