Python删除指定目录下的过期文件详解编程语言

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)

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/8283.html

(0)
上一篇 2021年7月18日 19:31
下一篇 2021年7月18日 19:31

相关推荐

发表回复

登录后才能评论