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程序设计有所帮助。

相关文章

解决pip install xxx报错SyntaxError: invalid syntax的问题

解决pip install xxx报错SyntaxError: invalid syntax的问题

python——pip install xxx报错SyntaxError: invalid syntax 在安装好python后,进入python运行环境后,因为我要用pip安装开发We...

对numpy数据写入文件的方法讲解

numpy数据保存到文件 Numpy提供了几种数据保存的方法。 以3*4数组a为例: 1. a.tofile("filename.bin") 这种方法只能保存为二进制文件,且不能保存当前...

python随机生成指定长度密码的方法

本文实例讲述了python随机生成指定长度密码的方法。分享给大家供大家参考。具体如下: 下面的python代码通过对各种字符进行随机组合生成一个指定长度的随机密码 python中的str...

python开发准备工作之配置虚拟环境(非常重要)

python开发准备工作之配置虚拟环境(非常重要)

之前作为菜鸟的我,从来不知道创建虚拟环境来开发python,都是使用全局的来开发项目,这样最后的结果是,所有的包全部安装在全局,也不能有好的在切换py2中切换,现在讲解在widow下使用...

python判断文件是否存在,不存在就创建一个的实例

如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f = open("D:/1.txt",'w')...