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

相关文章

Python整数与Numpy数据溢出问题解决

Python整数与Numpy数据溢出问题解决

某位 A 同学发了我一张截图,问为何结果中出现了负数? 看了图,我第一感觉就是数据溢出了。数据超出能表示的最大值,就会出现奇奇怪怪的结果。 然后,他继续发了张图,内容是 print(1...

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...

使用python获取电脑的磁盘信息方法

使用Python获取电脑的磁盘信息需要借助于第三方的模块psutil,这个模块需要自己安装,纯粹的CPython下面不具备这个功能。 在iPython交互界面中进行如下演示: 查看电脑的...

Python实现的文本简单可逆加密算法示例

本文实例讲述了Python实现的文本简单可逆加密算法。分享给大家供大家参考,具体如下: 其实很简单,就是把一段文本每个字符都通过某种方式改变(比如加1) 这样就实现了文本的加密操作,解密...

利用Python开发实现简单的记事本

利用Python开发实现简单的记事本

前言 本文的操作环境:ubuntu,Python2.7,采用的是Pycharm进行代码编辑,个人很喜欢它的代码自动补齐功能。 示例图 如上图,我们可以看到这个记事本主要分为三个模块:文...