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

相关文章

DJANGO-URL反向解析REVERSE实例讲解

DJANGO-URL反向解析REVERSE实例讲解

解决path中带参数的路径。 reverse(viewname,urlconf=None,args=None,Kwargs=None,current_app=None) book/vie...

python3中bytes和string之间的互相转换

前言 Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意...

python树的同构学习笔记

python树的同构学习笔记

一、题意理解 给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构的”。现给定两棵树,请你判断它们是否是同构的。 输入格式:输入给出2棵二叉树的信...

简单学习Python多进程Multiprocessing

简单学习Python多进程Multiprocessing

1.1 什么是 Multiprocessing 多线程在同一时间只能处理一个任务。 可把任务平均分配给每个核,而每个核具有自己的运算空间。 1.2 添加进程 Process 与线程类似,...

python itchat实现调用微信接口的第三方模块方法

itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。 使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。 当然,该api的使用远不止一个机器人...