Python删除指定目录下的过期文件

2022-03-11 00:00:00 删除 指定 过期

Python删除指定目录下的过期文件,这段代码可以用来在服务器上定期删除保存时间较久的日志文件。

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/24
功能描述: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)

以上代码在python3.9下测试通过。

相关文章