Home > Backend Development > Python Tutorial > python delete files before specified time interval

python delete files before specified time interval

不言
Release: 2018-04-24 13:41:17
Original
2514 people have browsed it

The following is a python example of deleting files before a specified time interval. It has a good reference value and I hope it will be helpful to everyone. Let's take a look together

Traverse the files in the specified folder, and obtain the file list of the specified type according to the file suffix name; according to the file path in the file list, obtain the "modification time" in the file attributes one by one. If the difference between "modification time" and "current system time" is greater than a certain value, the file will be deleted.

#!/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..."
Copy after login

Related recommendations:

Solve the permission error problem of python deleting files

The above is the detailed content of python delete files before specified time interval. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template