如果您不想使用RotatingFileHandler的简单示例。
您应该使用os.stat('filename').st_size
来检查文件大小。
import os
import sys
class RotatingFile(object):
def __init__(self, directory='', filename='foo', max_files=sys.maxint,
max_file_size=50000):
self.ii = 1
self.directory, self.filename = directory, filename
self.max_file_size, self.max_files = max_file_size, max_files
self.finished, self.fh = False, None
self.open()
def rotate(self):
"""Rotate the file, if necessary"""
if (os.stat(self.filename_template).st_size>self.max_file_size):
self.close()
self.ii += 1
if (self.ii<=self.max_files):
self.open()
else:
self.close()
self.finished = True
def open(self):
self.fh = open(self.filename_template, 'w')
def write(self, text=""):
self.fh.write(text)
self.fh.flush()
self.rotate()
def close(self):
self.fh.close()
@property
def filename_template(self):
return self.directory + self.filename + "_%0.2d" % self.ii
if __name__=='__main__':
myfile = RotatingFile(max_files=9)
while not myfile.finished:
myfile.write('this is a test')
运行这个之后...
[mpenning@Bucksnort ~]$ ls -la | grep foo_
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_01
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_02
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_03
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_04
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_05
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_06
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_07
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_08
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_09
[mpenning@Bucksnort ~]$