python删除过期文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了python删除过期文件的方法。分享给大家供大家参考。具体实现方法如下:

# remove all jpeg image files of an expired modification date = mtime
# you could also use creation date (ctime) or last access date (atime)
# os.stat(filename) returns (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
# tested with Python24  vegaseat 6/7/2005
import os, glob, time
root = 'D:\\Vacation\\Poland2003\\' # one specific folder
#root = 'D:\\Vacation\\*'     # or all the subfolders too
# expiration date in the format YYYY-MM-DD
xDate = '2003-12-31'
print '-'*50
for folder in glob.glob(root):
  print folder
  # here .jpg image files, but could be .txt files or whatever
  for image in glob.glob(folder + '/*.jpg'):
    # retrieves the stats for the current jpeg image file
    # the tuple element at index 8 is the last-modified-date
    stats = os.stat(image)
    # put the two dates into matching format  
    lastmodDate = time.localtime(stats[8])
    expDate = time.strptime(xDate, '%Y-%m-%d')
    print image, time.strftime("%m/%d/%y", lastmodDate)
    # check if image-last-modified-date is outdated
    if expDate > lastmodDate:
      try:
        print 'Removing', image, time.strftime("(older than %m/%d/%y)", expDate)
        #os.remove(image) # commented out for testing
      except OSError:
        print 'Could not remove', image

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python IDLE 错误:IDLE''s subprocess didn''t make connection 的解决方案

Python IDLE 错误描述: Subprocess Startup Error IDLE's subprocess didn't make connection. Eithe...

python中精确输出JSON浮点数的方法

有时需要在JSON中使用浮点数,比如价格、坐标等信息。但python中的浮点数相当不准确, 例如下面的代码:复制代码 代码如下:#!/usr/bin/env python import...

Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例

Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例

本文实例讲述了python从任意长度的可迭代对象中分解元素操作。分享给大家供大家参考,具体如下: 从某个可迭代对象中分解出N个元素,但是可迭代对象的长度可能超过N,会出现“分解值过多”的...

Django原生sql也能使用Paginator分页的示例代码

django-pagination这是一个python包,来自github上的一个项目,很容易用。 不过这是一个懒人工具,好吧(工具理性)。不过当一个页面有多处需要采用分页的话,就行不...

Python编程中NotImplementedError的使用方法

Python编程中raise可以实现报出错误的功能,而报错的条件可以由程序员自己去定制。在面向对象编程中,可以先预留一个方法接口不实现,在其子类中实现。 如果要求其子类一定要实现,不实现...