Tuesday, December 18, 2012

Remove log files using Python in Windows Server


I was working in Windows Server 2003 where one of our application service was creating a large log files every day and when the  log file used to become more than 2 GB the application rotate it to another new log file. I had to create a script to remove those old unnecessary log files.

I created a script using used Python 2.7 environment and add it to schedule task. Now it has been working fine.

#!/usr/bin/python -tt

import sys
import os

def main():
  filelist = []
  path = r'C:\test\log'
  if os.path.exists(path) == True:
    for f in os.listdir(os.getcwd()):
       if f.endswith('log'):
         lastmod_date = os.path.getmtime(f)
         f_tuple = lastmod_date , f
  if len(filelist) > 1: # if we have more than one log files then go to remove
    filelist.sort() # sort according to the lastmod_date
    filelist.pop() # remove the last item from the list as it is the current one
    for i in range(0,len(filelist)):
      os.remove(path + '\\'+ filelist[i][1])
if __name__ == '__main__':

Leave a Reply