Search code examples
pythondatepython-2.7for-loopmonthcalendar

Cycling through a list of months with years to check if file exists


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


Solution

  • 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.