The script is as follows:
#!/usr/local/python/bin/python # -*-coding=utf8 -*- import time import os, sys # Set how many days before deleting files N = 3 #To delete a path path = r'/tmp/wry/abc' 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 # Set how long before deleting files endfiletime = time.time() - 3600 * 24 * N if endfiletime > lastmodifytime: #if filename[-4:] == ".log": os.remove(filename) print "Delete files %s Success" % filename # Call the current function recursively if it is a directory elif os.path.isdir(filename): deletefile(filename) if __name__ == '__main__': deletefile(path)
The operation effect is as follows:
To run python under windows, scripts are needed, mainly to modify the output characters, otherwise it is garbled:
#!/usr/local/python/bin/python # -*-coding=utf8 -*- import time import os, sys #Set how many days before deleting files N = 3 path = r"E:\0 work\02 Routine\linux Script\delete N Day script\test".decode('utf-8').encode('GB2312') 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 #Set how long before deleting files endfiletime = time.time() - 3600 * 24 * N if endfiletime > lastmodifytime: #if filename[-4:] == ".log": os.remove(filename) print "Delete files %s Success".decode('utf-8').encode('GB2312') % filename #Call the current function recursively if it is a directory elif os.path.isdir(filename): deletefile(filename) if __name__ == '__main__': deletefile(path)
The output is as follows
Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ \ Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ operation and maintenance information table.xlsx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ new folder \ application architecture design V1.1.docx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ create new folder \ start stop document.xlsx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ start stop document.xlsx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script N days ago \ test \ abc \ application architecture design V1.1.docx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script before N days \ test \ abc \ operation and maintenance information table.xlsx succeeded Delete file E: e: \ 0 work \ 02 daily work \ linux script \ delete script before N days \ test \ abc \ operation and maintenance knowledge base start stop document.xlsx succeeded
Reference resources: python deletes files with the suffix. log 2 days ago
python delete files N days ago