Created
June 28, 2013 11:47
-
-
Save lazyval/5884136 to your computer and use it in GitHub Desktop.
Rotating file implementation for python. I'm ignoring any error handling and proper closing here
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import os.path | |
buffer_in_bytes = 10 * 100 * 100 | |
class RotatingFile: | |
def __init__(self, filename, max_files, lines_per_file): | |
self.file = open(filename, mode='w', buffering=buffer_in_bytes) | |
self.filename = filename | |
self.max_files = max_files | |
self.lines_per_file = lines_per_file | |
self.lines_written = 0 | |
def write(self, message): | |
if (self.lines_written >= self.lines_per_file): | |
self.rotate_file() | |
self.file.write(message) | |
self.lines_written += 1 | |
def rotate_file(self): | |
self.file.close() | |
name = self.filename | |
for f in reversed(range(1, self.max_files)): | |
src = name + '.' + str(f) | |
dst = name + '.' + str(f + 1) | |
file_exists = os.path.isfile(src) | |
if (file_exists): | |
os.rename(src, dst) | |
os.rename(name, name + '.1') | |
self.file = open(name, mode='w', buffering=buffer_in_bytes) | |
self.lines_written = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment