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


本文摘自php中文网,作者不言,侵删。

下面为大家分享一篇python 删除指定时间间隔之前的文件实例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

#!/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中函数count()的功能是什么

Python有栈吗

Python基础教程项目三之万能的xml

Python实现给照片换底色(附代码)

认识什么是PythonPython的优点和缺点

Python利用openpyxl库遍历sheet的实例

Python爬虫是什么?为什么把Python叫做爬虫?

Python都可以用来做什么

Python 的& 表示什么

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...