Python

특정기간 지난 파일 삭제

이쥬우 2023. 4. 24. 15:33
728x90

- 파일 이름이 날짜시간이어야 함.
- 경로는 IP로 단순히 정의했음.

#-*- coding: utf-8 -*-
 
import os, re
from datetime import date, timedelta
 
filePath = '경로/rawlog'
 
class LogRemover:
    def __init__(self, dPath = filePath, days = 7):
        self.defaultPath = dPath
        self.duDays = days
 
    def getFileList(self):
        ipCheck = re.compile(r'(\d+).(\d+).(\d+).(\d+)')
        fList = os.listdir(self.defaultPath)
        for ipFile in fList:
            if ipCheck.search(ipFile) != None:
                self.fileRemove(ipFile)
 
    def fileRemove(self, ipFile):
        dateCheck = re.compile(r'(\d{8})')
        tDay = date.today()
        _dDay = tDay - timedelta(self.duDays)
        dDay = str(_dDay).replace('-','')
        fullDir = os.path.join(self.defaultPath, ipFile)
        fList = os.listdir(fullDir)
        fList.sort()
        for fName in fList:
            _fName = dateCheck.search(fName)
            if _fName.group() >= dDay:
                break
            else:
                os.remove(os.path.join(fullDir, fName))
 
    def run(self):
        self.getFileList()
 
if __name__ == '__main__':
    m = LogRemover()
    m.run()
 
#EOF

 

[출처]
https://flowerinmyheart.tistory.com/entry/%ED%8A%B9%EC%A0%95%EA%B8%B0%EA%B0%84-%EC%A7%80%EB%82%9C-%ED%8C%8C%EC%9D%BC-%EC%82%AD%EC%A0%9C

728x90