Python刪除指定目錄下過期文件的2個(gè)腳本分享
腳本1:
這兩天用python寫了一個(gè)刪除指定目錄下過期時(shí)間的腳本。也可能是我初學(xué)python,對(duì)python還不夠熟習(xí),總覺得這個(gè)腳本用shell寫應(yīng)該更簡單也更容易些。
就功能上來說,該腳本已經(jīng)實(shí)現(xiàn)了我想要的效果,不過該腳本還不夠通用性,還有更多可以完善的地方。目前該腳本在python2.4下運(yùn)行良好。同時(shí),我在腳本中加入了對(duì)python版本的判斷,理論上2.7下也應(yīng)該可以正常使用。有環(huán)境的朋友可以幫忙測試一下。
該腳本不完善的地方在于,只能支持一級(jí)目錄下的文件刪除,還不支持目錄遞歸。同時(shí)過期文件的定義只能按week來做。
Python代碼:
#! /usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
import time,datetime
# 定義需要?jiǎng)h除文件的目錄
dir = '/data/webbak/'
# 被刪除文件寫入日志文件
logdir = '/var/log'
logfile = os.path.join(logdir, 'delete.log')
# 獲取當(dāng)前系統(tǒng)python版本
ver = sys.version
ver = ver.split(' ')
ver = ver[0]
# 將"Wed Jul 4 13:25:59 2012"格式的時(shí)間轉(zhuǎn)成“2012-07-02 14:50:15”格式的時(shí)間
# version是當(dāng)前系統(tǒng)python版本號(hào)
# time是"Wed Jul 4 13:25:59 2012"格式的時(shí)間
# 函數(shù)返回"2012-07-02 14:50:15"格式的時(shí)間
def string2time(str_time, version = ver):
version_l = version.split('.')[0:2]
ver = version_l[0] + '.' + version_l[1]
if (ver == '2.7'):
f_time = datetime.datetime.strptime(str_time, time_format)
f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
return f_time
elif(ver == '2.4'):
f_time = time.strptime(str_time, time_format)
f_time = datetime.datetime(*f_time[0:6])
return f_time
# 時(shí)間格式
time_format = "%a %b %d %H:%M:%S %Y"
# 取得當(dāng)前時(shí)間
today = datetime.datetime.now()
# 定義4個(gè)星期
four_weeks = datetime.timedelta(weeks=6)
# 4星期前的日期
four_weeks_ago = today - four_weeks
# 將時(shí)間轉(zhuǎn)成timestamps
four_weeks_ago_timestamps = time.mktime(four_weeks_ago.timetuple())
# 列出目錄中的所有文件
files = os.listdir(dir)
# 打開要?jiǎng)h除的文件日志
fh = open(logfile, "w+")
# 遍歷文件,打印出文件的創(chuàng)建時(shí)間
for f in files:
# 忽略掉.開頭的文件
if f.startswith('.'):
continue
# 忽略掉當(dāng)前目錄下的目錄
if os.path.isdir(os.path.join(dir,f)):
continue
# 獲得文件的modify時(shí)間,并轉(zhuǎn)換成timestamp格式
file_timestamp = os.path.getmtime(os.path.join(dir, f))
file_time_f = string2time(time.ctime(file_timestamp))
if float(file_timestamp) <= float(four_weeks_ago_timestamps):
fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,f) + "\n")
os.remove(os.path.join(dir,f))
# 關(guān)閉文件
fh.close()
腳本2:
實(shí)現(xiàn)類似下面的Shell命令的操作
Python代碼:
import os
import sys
import time
class DeleteLog:
def __init__(self,fileName,days):
self.fileName = fileName
self.days = days
def delete(self):
if os.path.isfile(self.fileName):
fd = open(self.fileName,'r')
while 1:
buffer = fd.readline()
if not buffer : break
if os.path.isfile(buffer):
os.remove(buffer)
fd.close()
elif os.path.isdir(self.fileName):
for i in [os.sep.join([self.fileName,v]) for v in os.listdir(self.fileName)]:
print i
if os.path.isfile(i):
if self.compare_file_time(i):
os.remove(i)
elif os.path.isdir(i):
self.fileName = i
self.delete()
def compare_file_time(self,file):
time_of_last_access = os.path.getatime(file)
age_in_days = (time.time()-time_of_last_access)/(60*60*24)
if age_in_days > self.days:
return True
return False
if __name__ == '__main__':
if len(sys.argv) == 2:
obj = DeleteLog(sys.argv[1],0)
obj.delete()
elif len(sys.argv) == 3:
obj = DeleteLog(sys.argv[1],int(sys.argv[2]))
obj.delete()
else:
print "usage: python %s listFileName|dirName [days]" % sys.argv[0]
sys.exit(1)
相關(guān)文章
python通過Windows下遠(yuǎn)程控制Linux系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python通過Windows下遠(yuǎn)程控制Linux系統(tǒng),實(shí)現(xiàn)對(duì)socket模塊認(rèn)識(shí),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
如何用Python數(shù)據(jù)可視化來分析用戶留存率
今天和大家來分享一些數(shù)據(jù)可視化方向的干貨,我們來嘗試用Python來繪制一下“漏斗圖”,感興趣的小伙伴和小編一起進(jìn)入課題吧,但愿大家會(huì)有所收獲2021-09-09
使用python加密主機(jī)文件幾種方法實(shí)現(xiàn)
本文主要介紹了使用python加密主機(jī)文件幾種方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的全過程
最近項(xiàng)目中采用了前后端分離的技術(shù),感覺有必要給大家總結(jié)下,所以下面這篇文章主要給大家介紹了關(guān)于python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的相關(guān)資料,需要的朋友可以參考下2022-06-06
回調(diào)函數(shù)的意義以及python實(shí)現(xiàn)實(shí)例
本篇文章主要介紹了回調(diào)函數(shù)的意義以及python實(shí)現(xiàn)實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

