[英]Pattern matching for current year and month in filename
我有這個初始位來提取當前月份和年份值。
目標是找到(並刪除)日志文件目錄中名稱格式為“access.log.2017-11”的所有文件(如果月份與當前月份不匹配)。
log_file_dir = '/home/eos/test/dir'
cur_date = datetime.date.today()
cur_month = cur_date.strftime('%m') # returns '11', '03'...
cur_year = cur_date.strftime('%Y') # returns 2001, 2017...
我嘗試使用glob但它似乎並沒有與我的想法相匹配:
os.chdir(log_file_dir)
glob.glob('./.log.cur_year-cur_month') # nope, not working
有沒有像'cur_year'這樣的var名稱可以插入到匹配表達式的模式中,以便找到它們?
當你寫'./.log.cur_year-cur_month'
它被認為是一個完整的字符串。 如果你想使用變量,你必須將它們與字符串連接起來,而不是將它們放在引號中: './.log.' + cur_year + '-' + cur_month
'./.log.' + cur_year + '-' + cur_month
glob.glob('./.log.cur_year-cur_month')
沒有格式,沒有字符串插值或任何通配符。 這意味着glob將只查找一個文件,字面意思是'./.log.cur_year-cur_month'
。 此文件可能不在您的文件夾中。
你可以使用:
cur_date.strftime('*.log.%Y-%m')
作為glob模式 。 它應該為您提供以.log.2017-11
結尾的每個文件。
你需要一個glob模式*.log.2017-11
,這可以創建如下:
from datetime import datetime
import glob
log_file_dir = '/home/eos/test/dir'
log_file_dir = r'e:\python temp'
cur_date = datetime.today().strftime('%Y-%m')
for filename in glob.glob(os.path.join(log_file_dir, '*.log.{}'.format(cur_date))):
os.remove(filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.