Home > Article > Backend Development > python delete files before specified time interval
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..."
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!