Python把csv檔案中的資訊寫入字典中指令碼(嘗試)
阿新 • • 發佈:2019-02-04
該段程式碼,只供參考,與期望不符合,後期會附上,完成的指令碼原始碼!
#coding=utf8 import csv class GenExceptData(object): def __init__(self): try: self.dataDic={} self.mdbuffer=[] #開啟工作薄 csvHand=open("20170510174450.csv","r") readcsv=csv.reader(csvHand) for row in readcsv: self.mdbuffer.append(row) #把資料按 按照相應格式寫入excel表中 self.readDataToDicl() #儲存檔案 except Exception,e: print "Read Excel error:",e finally: csvHand.close() def readDataToDicl(self): try: rowNumber=len(self.mdbuffer) currentrow=1 propertyJson={} for row in range(1,rowNumber): temp={} item=self.mdbuffer[row] currentItem=self.mdbuffer[currentrow] mdEvent= currentItem[0].decode("gbk") serviceId= currentItem[2].decode("gbk") propertyName=item[3].decode("gbk") propertyValue=item[4].decode("gbk") if item[0]==currentItem[0] and item[2]==currentItem[2]: print row , currentrow,mdEvent,serviceId,propertyName,propertyValue temp["serviceId"]=serviceId temp[propertyName]=propertyValue propertyJson.update(temp) temp.clear() continue else: currentrow=row currentItem=self.mdbuffer[currentrow+1] mdEvent= currentItem[0].decode("gbk") serviceId= currentItem[2].decode("gbk") proName=currentItem[3].decode("gbk") proValue=currentItem[4].decode("gbk") temp["serviceId"]=serviceId temp[proName]=proValue print row , currentrow,mdEvent,serviceId,propertyName,propertyValue propertyJson.update(temp) temp.clear() continue break for key,val in propertyJson.items(): print key,"=",val.encode("utf8") print "*"*50 self.dataDic[mdEvent]=propertyJson ''' for value in self.dataDic.values(): for key,val in value.items(): print key,"=",val.encode("utf8") print "*"*50 ''' except Exception,e: print "Reading Data TO Dic Error:",e def test(): GenExceptData() if __name__=="__main__": test()