Reputation: 388
I have this initial bit to extract the current month and year value.
The goal is to find (and remove) all files in a log file directory with a name format of 'access.log.2017-11' if the month does not match the current month.
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...
I tried with glob but it doesn't seem to make a match for what I had in mind likewise:
os.chdir(log_file_dir)
glob.glob('./.log.cur_year-cur_month') # nope, not working
Is there anywhere that the var names like 'cur_year' can be inserted in a pattern matching expression so that it will find them?
Upvotes: 2
Views: 1659
Reputation: 46759
You need a glob pattern *.log.2017-11
, this can be created as follows:
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)
Upvotes: 1
Reputation: 54223
glob.glob('./.log.cur_year-cur_month')
there's no formatting, no string interpolation or any wildcard. It means that glob will look for exactly one file, which is literally './.log.cur_year-cur_month'
. This file probably isn't in your folder.
You could use:
cur_date.strftime('*.log.%Y-%m')
as the glob pattern. It should give you every file ending with .log.2017-11
.
Upvotes: 1
Reputation: 163
When you write './.log.cur_year-cur_month'
it is considered as a whole string. If you want to use the variables you have to concatenate them with the string and not putting them into quotes : './.log.' + cur_year + '-' + cur_month
Upvotes: 1