1. 程式人生 > >python指令碼刪除n天前檔案可用於windows,linux並且支援跨平臺

python指令碼刪除n天前檔案可用於windows,linux並且支援跨平臺

指令碼如下:

#!/usr/local/python/bin/python
# -*-coding=utf8 -*-
import time
import os, sys

# 設定刪除多少天前的檔案
N = 3
#要刪除路徑
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
            # 設定刪除多久之前的檔案
            endfiletime = time.time() - 3600 * 24 * N
            if endfiletime > lastmodifytime:
                #if filename[-4:] == ".log":
                os.remove(filename)
                print "刪除檔案 %s 成功" % filename
        # 如果是目錄則遞迴呼叫當前函式
        elif os.path.isdir(filename):  
            deletefile(filename)

if __name__ == '__main__':
    deletefile(path)

執行效果如下:

在windows下執行python需要指令碼,主要修改輸出字元,否則為亂碼:

#!/usr/local/python/bin/python
# -*-coding=utf8 -*-
import time
import os, sys

#設定刪除多少天前的檔案
N = 3  
path = r"E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試".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
            #設定刪除多久之前的檔案
            endfiletime = time.time() - 3600 * 24 * N  
            if endfiletime > lastmodifytime:
                #if filename[-4:] == ".log":
                os.remove(filename)
                print "刪除檔案 %s 成功".decode('utf-8').encode('GB2312') % filename
        #如果是目錄則遞迴呼叫當前函式
        elif os.path.isdir(filename):  
            deletefile(filename)

if __name__ == '__main__':
    deletefile(path)

輸出結果如下

刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\2\_應用架構設計 V1.1.docx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\2\運維資訊表.xlsx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\2\新建資料夾\應用架構設計 V1.1.docx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\2\新建資料夾\啟停文件.xlsx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\2\啟停文件.xlsx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\應用架構設計 V1.1.docx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\運維資訊表.xlsx 成功
刪除檔案 E:\0工作\02日常工作\linux指令碼\刪除N天前指令碼\測試\abc\運維知識庫啟停文件.xlsx 成功

參考:python 刪除2天前後綴為.log的檔案
python刪除N天前檔案