2013-05-16 183 views
0

我有幾個包含流數據的數據文件。例如,將零寫入空白單元格python

9/12/1999 0 
13/12/1999 2544  
14/12/1999 2552  
15/12/1999  
16/12/1999   
18/12/1999 3039  
19/12/1999 3043  

我寫了一個代碼讀取所有的數據文件,並寫入到具有格式 日期初級流瑜伽中級課程等新的輸出文件

我也寫在連續的日期(那裏不是該日期的數據,將0寫入輸出文件)。我在下面的腳本中沒有包括這一點。

我遇到的問題是,當數據文件中有一行帶日期但沒有流量數據(例如,上面例子中的第4,5行)。該代碼給了我空白值,而不是0.我認爲這是一個簡單的事情,但我無法弄清楚。任何人都可以幫助我嗎? 我的代碼是

for Qfilename in Q_filenamelist: 
    Qfileopen = open(Qfilename,'r') 
    for line in Qfileopen: 
     line = line.rstrip()   
     if not line.startswith("and") and not line.startswith("Time") and not line.startswith("Date"):  #ignore headers 
      Qwordslist = line.split(',') 
      time = Qwordslist[0] 
      flow = Qwordslist[1] 
      if not time in time_list: 
       time_list.append(time) 
      index = time+" "+Qfilename 
      Qourdict[index] = flow    

    Qfileopen.close()   
time_list.sort(key=lambda x: datetime.strptime(x,'%d/%m/%Y')) 
#write output data 
outfile = open(outfilename,'w') 
outfile.write("Date,") 
for Qfilename in Q_filenamelist: 
    Qfilename = Qfilename.split(".")[0] 
    outfile.write(Qfilename+',') 
outfile.write('\n') 

for time in time_list: 
    outfile.write(time+',') 
    for Qfilename in Q_filenamelist: 
     index = time+" "+Qfilename   
     grabflow = Qourdict.get(index,"0.0") 
     if grabflow == " ": 
      outfile.write("0.0"+',') 
     else: 
      outfile.write(str(grabflow)+',') 
    outfile.write('\n') 
outfile.close() 

非常感謝。

+1

除非這是功課,HTTP:/ /docs.python.org/2/library/csv.html – Patashu

回答

0

作爲一個猜測,你可以嘗試:

Qourdict[index] = flow if flow.strip() else '0' 

相反的:

Qourdict[index] = flow 

沒有太多去......

相關問題