0

我正在尝试循环浏览从 2012 年和 11 月开始的月份列表,一直到当前年份和月份。

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 ""

任何有关如何实现此目标或建议的建议或建设性意见将不胜感激。非常感谢

4

2 回答 2

7

我可能会这样做:

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)

如果您需要我详细说明它的工作原理,请告诉我。

于 2013-10-30T22:38:04.813 回答
4
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
于 2013-10-30T22:54:24.463 回答