封装print方法,通过print方法的file形参指定被输出文件:
import datetime
import os
import zipfile
class Log():
def __init__(self):
if not os.path.exists('Log/GUI'):
os.makedirs('Log/GUI')
if not os.path.exists('Log/GUI/GUI.log'):
with open('Log/GUI/GUI.log','w') as file:
pass
def ZIP(self):
if os.path.exists('Log/GUI/GUI.log'):
now=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
with zipfile.ZipFile(f'Log/GUI/GUI_{now}.zip', 'w') as zipf:
zipf.write('Log/GUI/GUI.log', arcname='GUI.log')
os.remove('Log/GUI/GUI.log')
def WriteInformation(self,message):
message=f'{str(datetime.datetime.now())}——Information——{message}'
if os.path.exists('Log/GUI/GUI.log'):
with open('Log/GUI/GUI.log', 'a') as log:
print(message,file=log)
def WriteError(self,message):
message=f'{str(datetime.datetime.now())}——Error——{message}'
if os.path.exists('Log/GUI/GUI.log'):
with open('Log/GUI/GUI.log', 'a') as log:
print(message,file=log)
调用:
logObject=Log()
logObject.WriteInformation('The software starts running.')