python 删除指定时间间隔之前的文件实例

yipeiwu_com5年前Python基础

遍历指定文件夹下的文件,根据文件后缀名,获取指定类型的文件列表;根据文件列表里的文件路径,逐个获取文件属性里的“修改时间”,如果“修改时间”与“系统当前时间”差值大于某个值,则删除该文件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Document: Remove Synctoycmd sync expired .tmp files"""
import os
import time
import datetime
def diff():
  '''time diff'''
  starttime = datetime.datetime.now()
  time.sleep(10)
  endtime = datetime.datetime.now()
  print "time diff: %d" % ((endtime-starttime).seconds)
def fileremove(filename, timedifference):
  '''remove file'''
  date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
  print date
  now = datetime.datetime.now()
  print now
  print 'seconds difference: %d' % ((now - date).seconds)
  if (now - date).seconds > timedifference:
    if os.path.exists(filename):
      os.remove(filename)
      print 'remove file: %s' % filename
    else:
      print 'no such file: %s' % filename
FILE_DIR = 'D:/'
if __name__ == '__main__':
  print 'Script is running...'
  #diff()
  while True:
    ITEMS = os.listdir(FILE_DIR)
    NEWLIST = []
    for names in ITEMS:
      if names.endswith(".txt"):
        NEWLIST.append(FILE_DIR + names)
    #print NEWLIST
    for names in NEWLIST:
      print 'current file: %s' % (names)
      fileremove(names, 10)
    time.sleep(10)
  print "never arrive..."

以上这篇python 删除指定时间间隔之前的文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python遍历类中所有成员的方法

本文实例讲述了python遍历类中所有成员的方法。分享给大家供大家参考。具体分析如下: 这段代码自定义了一个类,类包含了两个成员title和url,在类的内部定义了一个函数list_al...

详解Python函数作用域的LEGB顺序

本文为大家介绍了Python函数作用域的查找顺序,供大家参考,具体内容如下 1.什么是LEGB? L:local 函数内部作用域 E:enclosing 函数内部与内嵌函数之间 G...

flask-socketio实现WebSocket的方法

【flask-socektio】 之前不知道在哪个场合下提到过如何从web后台向前台推送消息。听闻了反向ajax技术这种模式之后,大呼神奇,试了一下之后发现也确实可以用。不过,反向aj...

详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

在用pandas包和numpy包对数据进行分析和计算时,经常用到DataFrame和array类型的数据。在对DataFrame类型的数据进行处理时,需要将其转换成array类型,是以下...

将pandas.dataframe的数据写入到文件中的方法

将pandas.dataframe的数据写入到文件中的方法

导入实验常用的python包。如图2所示。 【import pandas as pd】pandas用来做数据处理。【import numpy as np】numpy用来做高维度矩阵运算....