python 刪除指定時間間隔之前的文件

不言
發布: 2018-04-24 13:41:17
原創
2437 人瀏覽過

下面要為大家分享一篇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 刪除指定時間間隔之前的文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!