runtime
190 / 500
question 190 Files & Directories · hard

Rotate a log file

A log that only ever grows becomes impossible to open. Write a function that rotates it: the newest lines stay in the log, and older lines move to an archive file next to it.

Functionrotate_log(path, keep)
Whenthe log has more than keep lines; otherwise nothing changes and no archive is created
Archivethe older lines are added, in order, to the end of path + ".1" (created if missing, never emptied)
Logafterwards holds only its last keep lines, each ending with \n; keep may be 0
Returnshow many lines were moved to the archive
Examples
callrotate_log('app.log', 2)returns3
callrotate_log('short.log', 5)returns0

Loading your progress…

Rotate a log file — Python practice · Runtime