原文件名为“web.log","web.log.1","web.log.2",运行后文件名改为“web.log.1","web.log.2","web.log.3"
采用递归的方式,依次增加文件编号
import os
import shutil
def rotate_log_file(path):
if not os.path.exists(path):
raise IOError("log not exist")
else:
file_path,old_name=os.path.split(path)
new_name=make_version(old_name)
new_path=os.path.join(file_path,new_name)
if os.path.exists(new_path):
rotate_log_file(new_path)
shutil.move(path,new_path)
def make_version(old_name):
result = list(old_name.split("."))
if result[-1]=="log":
return old_name+"."+"1"
else:
return old_name[:len(result[-1])*(-1)] + str(int(result[-1])+1)
if __name__=="__main__":
path=r"C:\Users\Administrator\Desktop\python\test\web.log"
rotate_log_file(path)