Reputation: 1391
I am trying to cycle through a list of months with years starting from the year of 2012 and month of November, all the way up to the current year and month.
start_year = "2012"
start_month = "November"
month = start_month
year = start_year
# some sort of for loop or cycle here
try:
with open('{} {}.csv'.format(month, year)):
CSVFile = True
if CSVFile:
print "do something cool here"
except IOError:
CSVFile = False
print ""
Any advice or constructive comments on how to achive this or advice would be greatly appreciated. Thanks SMNALLY
Upvotes: 0
Views: 133
Reputation: 114025
import datetime as dt
startYear = 2012
startMonth = 11
delta = 1
curr = dt.datetime(year=startYear, month=startMonth, day=1)
now = dt.datetime.now()
endYear = now.year
endMonth = now.month
while dt.datetime(year=year+(delta/12), month=month+(delta%12),day=1) <= now:
try:
with open('{} {}.csv'.format(month, year)):
CSVFile = True
if CSVFile:
print "do something cool here"
except IOError:
CSVFile = False
print ""
delta += 1
Upvotes: 4
Reputation: 37344
I would probably do this as follows:
import datetime, os
current_month = datetime.date.today().replace(day=1)
# this could be more concise if `start_month` were the month number rather than month name
possible_month = datetime.datetime.strptime('%s %s' % (start_month, start_year), '%B %Y').date()
while possible_month <= current_month:
csv_filename = possible_month.strftime('%B %Y') + '.csv'
if os.path.exists(csv_filename):
CSVFile = True
# do something cool here, and maybe break the loop if you like
possible_month = (possible_month + datetime.timedelta(days=31)).replace(day=1)
Let me know if you need me to expand on how that works.
Upvotes: 7