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

相关文章

Tensorflow环境搭建的方法步骤

Tensorflow环境搭建的方法步骤

What? 我们需要通过VMware虚拟机平台+Ubuntu虚拟机+安装pip的方式来搭建TensorFlow的环境。 官网参考文档地址:https://www.tensorflow.o...

Python使用bs4获取58同城城市分类的方法

本文实例讲述了Python使用bs4获取58同城城市分类的方法。分享给大家供大家参考。具体如下: # -*- coding:utf-8 -*- #! /usr/bin/python...

简单的编程0基础下Python入门指引

简单的编程0基础下Python入门指引

 你曾经想知道计算机是如何工作的吗?尽管我们不能在一篇文章里面教会你所有的东西,但是可以通过学习如何写出你自己的程序来获得一个良好的开端。在这篇Python教程中,你将会学到计...

Django 多环境配置详解

本文也是开发项目中的一个小经验Tip,虽然很简单,但对很多朋友也有小帮助。 我们实际工程中,可能遇到开发环境、预上线环境、线上环境等环境场景,应用配置因此可能有所不同。 我的经验是利用环...

Django之模型层多表操作的实现

Django之模型层多表操作的实现

一、创建模型 1,一对多关系 一本书只有一个出版社,一个出版社可以出版多本书,从而书与出版社之间就构成一对多关系,书是‘多'的一方,出版社是‘一'的一方,我们在建立模型的时候,把外键写在...