python删除过期文件的方法

yipeiwu_com5年前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实现的多线程端口扫描功能示例

python实现的多线程端口扫描功能示例

本文实例讲述了python实现的多线程端口扫描功能。分享给大家供大家参考,具体如下: 下面的程序给出了对给定的ip主机进行多线程扫描的Python代码 #!/usr/bin/env...

在Python中通过getattr获取对象引用的方法

getattr函数 (1)使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 >>> li = ["Larry", "Curly"] >...

Python操作mysql数据库实现增删查改功能的方法

本文实例讲述了Python操作mysql数据库实现增删查改功能的方法。分享给大家供大家参考,具体如下: #coding=utf-8 import MySQLdb class Mysq...

Python实现图片转字符画的示例代码

Python实现图片转字符画的示例代码

初学Python,在网上看到Python图片转字符画的教程,我也来尝试下。 首先我们要用到Python的PIL库的Image模块,PIL(Python Imaging Library...

Python实现的最近最少使用算法

本文实例讲述了Python实现的最近最少使用算法。分享给大家供大家参考。具体如下: # lrucache.py -- a simple LRU (Least-Recently-Use...