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

相关文章

详解Python3的TFTP文件传输

详解Python3的TFTP文件传输

TFTP文件传输 功能: 1、获取文件列表 2、上传文件 3、下载文件 4、退出 第一部分,TftpServer部分。 ①导入相关模块 from socket import * im...

python读文件的步骤

python读文件的步骤

python怎么读文件? 首先,在桌面上建立一个txt文档,在上面输入以下内容: 你好。Hello.abcdefg啊不错的风格 查看文件的属性,获取文件的绝对路径: D:\Hi...

Django 开发调试工具 Django-debug-toolbar使用详解

Django 开发调试工具 Django-debug-toolbar使用详解

django-debug-toolbar 介绍 django-debug-toolbar 是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多...

python 示例分享---逻辑推理编程解决八皇后

可以和Haskell , Prolog 一样做到模式匹配, 建立逻辑推到规则,描述问题,得出答案。 from pyDatalog import pyDatalog pyDatalo...

python中input()与raw_input()的区别分析

python中input()与raw_input()的区别分析

使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 纯数字输入 当输入为纯数字时 input返回的是数值类型,如int,f...