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:
os.chdir(path)
for f in os.listdir(os.getcwd()):
if f.endswith('log'):
lastmod_date = os.path.getmtime(f)
f_tuple = lastmod_date , f
filelist.append(f_tuple)
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])
return
if __name__ == '__main__':
main()