Python deletes the file below the specified folder based on the file change date

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.