import os
import sys
from datetime import timedelta, datetime
import logging
def main():
today = datetime.dateime.today().strftime('%y-%m-%d')
logging.basicConfig(filename='Logs/'+today+'.log', level = logging.DEBUG)
logging.info('Test Log: INFO')
logging.warning('Test log: WARNING')
logging.debug('Test log: DEBUG')
clear_old_logs()
def clear_old_logs():
today = datetime.date.today()
last_day_prev_month = today - datetime.timedelta(days=today.day)
same_day_prev_month = last_day_prev_month.replace(day=today.day)
test_date = '2018-06-11'
change_dir = os.open("Logs", os.O_RDONLY)
change_dir = os.fchdir(change_dir)
print "Current Directory: %s" % os.getcwd()
print "Directory contents: %s" %os.listdir(os.getcwd())
test_file = test_date+'.log'
print(test_file)
os.remove(test_file)
if __name__ == '__main__':
main()
以上是记录和删除该日志文件的基本脚本。手头的问题是尝试动态删除文件。目标是删除超过一个月的日志,因此删除same_day_prev_month
。 os.remove()
有效,但我不确定如何动态执行此操作。我试过的方法如下,但它没有删除任何东西。
def clear_old_logs():
today = datetime.date.today()
last_day_prev_month = today - datetime.timedelta(days=today.day)
same_day_prev_month = last_day_prev_month.replace(day=today.day)
test_date = '2018-06-11'
change_dir = os.open("Logs", os.O_RDONLY)
change_dir = os.fchdir(change_dir)
mylist = os.listdir(os.getcwd())
#file = same_day_prev_month+'.log' #I commented this out due to testing with the current date
file = test_date+'.log' #just testing to see if I can remove log files created today with an if
for logs in mylist:
if file >= logs:
os.remove(logs)
else:
continue