2013-10-30 49 views
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 "" 

任何意見或建設性的意見,如何實現這個或建議將不勝感激。 感謝SMNALLY

回答

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) 

讓我知道,如果你需要我就如何工作的展開。

+0

'curr',也許? – inspectorG4dget

+2

@ inspectorG4dget我愛讀你的轉換,讓我笑:P – Ryflex

+2

@Hyflex:睡眠剝奪了我爲一個非常熱鬧的派對嘉賓(微調微調wink wink) – inspectorG4dget

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 
+0

整潔的贖回,簡單,有效和類似於操作 – Ryflex

+2

要麼是我的轉而忽視某些事情,或者這實際上並沒有增加候選人的日期。 –

+2

@PeterDeGlopper:你說得對。我只是修復它。我應該真的停止編碼沒有睡眠或咖啡 – inspectorG4dget

相關問題