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中使用MELIAE分析程序内存占用实例

写的dht协议搜索的程序,这几天优化了一下发现速度确实快了好多。但是出现了一个新的问题,内存直接飙升,我开了十个爬虫占用内存800m。开始我以为是节点太多了,找了几个小问题修改一下,发现...

Python从数据库读取大量数据批量写入文件的方法

使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将数据加载进内存,这时我们需要将数据进行预处理,分批次加载进内存。 下面是代码作用是将数据从数据库读取出来分批次写入txt文本文...

Python随机生成手机号、数字的方法详解

本文实例讲述了Python随机生成手机号、数字的方法。分享给大家供大家参考,具体如下: Python随机产生手机号、数字。代码如下: # -*- coding:gbk -*- imp...

Python和Go语言的区别总结

什么是Python? Python是一种功能强大的高级编程语言,主要用于科学和工程计算。它是一种高效的语言,优雅务实,简单而强大,适合新手和专业人士的编程。 Python支持多种编程范例...

利用pytorch实现对CIFAR-10数据集的分类

步骤如下: 1.使用torchvision加载并预处理CIFAR-10数据集、 2.定义网络 3.定义损失函数和优化器 4.训练网络并更新网络参数 5.测试网络 运行环境: win...