Summary of how Python deletes objects of a specified date

Source: Internet
Author: User

Python script execution Shell, execute Python script via crontab

The code is as follows Copy Code

#!/usr/bin /env python
#-*-coding:utf-8-*-

Import OS
Import time
Import datetime
Import subprocess

Tod Ay =datetime.date.today ()
Deltadays = Datetime.timedelta (Days=1)     #确定日期差额, such as the day before yesterday days=2
Yesterday = today-deltadays

Month = yesterday.strftime ('%b ')
date = Yesterday.strftime ('%d ')

Command1 = "Ls-hl/log1 | grep '%s ' | awk ' {print i$9} ' i= '/log1/' | Xargs RM "% (month, date)
Command11 =" Ls-hl/log1 | grep '%s %s ' | awk ' {print i$9} ' i= '/log1/' | Xargs RM "% (month, date)
Command2 =" Ls-hl/log2 | grep '%s ' | awk ' {print i$9} ' i= '/log2/' | Xargs RM "% (month, date)
Command22 =" Ls-hl/log2 | grep '%s %s ' | awk ' {print i$9} ' i= '/log2/' | Xargs rm% (month, date)

Os.system (Command1)
Os.system (command11)
Os.system (Command2)
Os.system ( COMMAND22)

Attention

The code is as follows Copy Code
ls-hl/log2 | grep '%s ' | awk ' {print i$9} ' i= '/log2/' | Xargs RM

This shell command is best done through Python execution shell promise to look at the specific file listed in the format to prevent invalid

The code is as follows Copy Code
Print Os.system ("ls-hl/log2")

The result can be obtained after running. And then modify it according to the specific circumstances.


Example 2, the day before the deletion date.

The code is as follows Copy Code

Import datetime
Import time

def get_yestoday (mytime):
Myday = datetime.datetime (int (mytime[0:4)), int (mytime[4:6]), int (mytime[6:8))
#now = Datetime.datetime.now ()
Delta = Datetime.timedelta (days=-1)
My_yestoday = myday + Delta
My_yes_time = My_yestoday.strftime ('%y%m%d ')
Return My_yes_time

example, delete files within a specified time within a folder

The code is as follows Copy Code

#-*-coding=gbk-*-
Import OS
Import time

def listdir (Filedir):
For Eachfile in Os.listdir (filedir):
If Os.path.isfile (filedir+ "/" +eachfile): #如果是文件, to determine the last modified time, match the conditions for deletion
FT = Os.stat (filedir+ "/" +eachfile);
ltime = Int (ft.st_mtime); #获取文件最后修改时间
The last modification time of the "+path+"/"+eachfile+" of the #print "+str" (ltime);
ntime = Int (Time.time ()) -3600*3; #获取现在时间减去3h
If Ltime<=ntime:
Print "I want to delete the file" +filedir+ "/" +eachfile;
Os.remove (filedir+ "/" +eachfile); #删除3小时前的文件

Elif Os.path.isdir (filedir+ "/" +eachfile): #如果是文件夹, continue recursion
Listdir (filedir+ "/" +eachfile);

if __name__ = = ' __main__ ':
Path = "E:/offlinefiles"; #规定目录
While True: #持续
Time.sleep (600); #减少资源利用率 600s seconds at a time
Print "3600s wake up";
Listdir (path);

Or

The code is as follows Copy Code

Import OS
Import Sys
Import time
Class Deletelog:

def __init__ (self,filename,days):
Self.filename = FileName
Self.days = Days
def delete (self):
If Os.path.isfile (self.filename):
FD = open (Self.filename, ' R ')
While 1:
Buffer = Fd.readline ()
If not buffer:break
If Os.path.isfile (buffer):
Os.remove (buffer)
Fd.close ()
Elif Os.path.isdir (self.filename):
For i in [Os.sep.join ([self.filename,v]) for V in Os.listdir (Self.filename)]:
Print I
If Os.path.isfile (i):
If Self.compare_file_time (i):
Os.remove (i)
Elif Os.path.isdir (i):
Self.filename = i
Self.delete ()
def compare_file_time (self,file):
time_of_last_access = os.path.getatime (file)
Age_in_days = (Time.time ()-time_of_last_access)/(60*60*24)
If Age_in_days > Self.days:
Return True
Return False
if __name__ = = ' __main__ ':
If Len (sys.argv) = = 2:
obj = Deletelog (sys.argv[1],0)
Obj.delete ()
Elif len (sys.argv) = = 3:
obj = Deletelog (Sys.argv[1],int (sys.argv[2))
Obj.delete ()
Else
Print "Usage:python%s listfilename|dirname [days]"% sys.argv[0]
Sys.exit (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.