After a day of trying, finally wrote a script to clean up the log file, the source code is as follows:
#!/usr/bin/python
#-*-coding=utf8-*-
Import time
Import OS
N = 1 #设置删除多少天钱的文件
def deletefile (path):
For Eachfile in Os.listdir (path):
filename = Os.path.join (path,eachfile)
If Os.path.isfile (filename):
LastModifyTime = Os.stat (filename). st_mtime
print ' ====================== '
Print "Current time is:%s"% time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Time.time ()))
The last modified time for the print "%s" File was:%s "% (Filename,time.strftime ("%y-%m-%d%h:%m:%s ", Time.localtime (lastmodifytime)))
The print "%s file was created at:%s"% (Filename,time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Os.stat (filename). st_ctime)))
Endfiletime = Time.time ()-3600 * N #设置删除多久之前的文件
Print "Delete files up to time:%s"% time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Endfiletime))
If Endfiletime > LastModifyTime:
Print "I want to delete file:%s"% filename
Os.remove (filename)
Elif os.path.isdir (filename): #如果是目录则递归调用当前函数
DeleteFile (filename)
if __name__ = = ' __main__ ':
Path = r "D:\python_script\log" #指定删除的目录位置
DeleteFile (PATH)
Note: Where print can be commented out, to avoid output to the console, because this is used in Windows Pycharm editing, directly into the Linux may appear garbled characters, please adjust the Linux character set or change the character itself into English can
This article is from the "Dong Yonggang blog" blog, make sure to keep this source http://dongyonggang.blog.51cto.com/9784442/1845234
Python deletes the file below the specified folder based on the file change date