Python 刪除指定日期的檔案方法總結

來源:互聯網
上載者:User

python指令碼執行shell,通過crontab執行python指令碼

 代碼如下 複製代碼

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

import os
import time
import datetime
import subprocess

today =datetime.date.today()
deltadays = datetime.timedelta(days=1)    #確定日期差額,如前天 days=2
yesterday = today - deltadays

month = yesterday.strftime('%b')
date = yesterday.strftime('%d')

command1 = "ls -hl /log1 | grep '%s %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 %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)

注意

 代碼如下 複製代碼
ls -hl /log2 | grep '%s  %s' | awk '{print i$9}' i='/log2/' | xargs rm

這段shell命令最好是通過python執行shell答應看下具體的檔案列出來的格式,防止無效

 代碼如下 複製代碼
print os.system("ls -hl /log2")

這樣運行後就能得出結果。然後根據具體情況修改就好了。


例子2,刪除日期的前一天 .

 代碼如下 複製代碼

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

例子,刪除檔案夾內規定時間內的檔案

 代碼如下 複製代碼

#-*-coding=gbk -*-
import os
import time

def listDir(fileDir):
     for eachFile in os.listdir(fileDir):
        if os.path.isfile(fileDir+"/"+eachFile):   #如果是檔案,判斷最後修改時間,符合條件進行刪除
            ft = os.stat(fileDir+"/"+eachFile);
            ltime = int(ft.st_mtime); #擷取檔案最後修改時間
            #print "檔案"+path+"/"+eachFile+"的最後修改時間為"+str(ltime);
            ntime = int(time.time())-3600*3; #擷取現在時間減去3h
            if ltime<=ntime :        
                print "我要刪除檔案"+fileDir+"/"+eachFile;
                os.remove(fileDir+"/"+eachFile);   #刪除3小時前的檔案

        elif os.path.isdir(fileDir+"/"+eachFile) :    #如果是檔案夾,繼續遞迴
            listDir(fileDir+"/"+eachFile);
   
if __name__ == '__main__':
    path = "E:/offlinefiles";   #規定目錄
    while True :    #持續
        time.sleep(600);   #減少資源使用率  600s秒一次
        print "3600s  wake up";
        listDir(path);

或者

 

 代碼如下 複製代碼

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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.