国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python把csv數據寫入list和字典類型的變量腳本方法

2020-02-15 21:52:26
字體:
來源:轉載
供稿:網友

如下所示:

#coding=utf8import csv import logginglogging.basicConfig(level=logging.DEBUG,        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',        datefmt='%a, %d %b %Y %H:%M:%S',        filename='readDate.log',        filemode='w')'''該模塊的主要功能,是根據已有的csv文件,通過readDataToDicl函數,把csv中對應的部分,寫入字典中,每個字典當當作一條json數據'''class GenExceptData(object):  def __init__(self):    try:      #存放csv中讀取的數據      self.mdbuffer=[]      #打開csv文件,設置讀的權限      csvHand=open("20170510174450.csv","r")      #創建讀取csv文件句柄      readcsv=csv.reader(csvHand)      #把csv的數據讀取到mdbuffer中      for row in readcsv:          self.mdbuffer.append(row)       #把數據穿件為為字典類型的      #self.readDataToList()      #保存文件    except Exception,e:      logging.error("Read Excel error:"+e)     finally:      #關閉csv文件      csvHand.close()   def readDataToList(self):    try:      #獲取mdbuffer中的元素個數      rowNumber=len(self.mdbuffer)      #設置當前行號      currentrow=1      #設置json數據的屬性值      propertyJson={}      #propertyJsonList=[]      #count=0      #讀取列表中的元素        dataList=[]       try:         for row in range(1,rowNumber):          #創建一個臨時變量用來存取一次循環的屬性鍵值          temp={}                    #獲取列表中一個元素          item=self.mdbuffer[row]          #獲取當前元素,當前元素代表的是每個          #事件起始的位置          currentItem=self.mdbuffer[currentrow]          #獲取serviceId并進行解碼          serviceId= currentItem[2].decode("gbk")          #獲取屬性并進行解碼,把解碼的值存入propertyName          propertyName=item[3].decode("gbk")          #獲取屬性值并進行解碼,把解碼的值存入propertyValue          propertyValue=item[4].decode("gbk")          try:            #判斷埋點事件與serviceId是否相等            if item[0]==currentItem[0] and item[2]==currentItem[2]:              #把serviceId方式字典propertyJson中              propertyJson["serviceId"]=serviceId               #把屬性/值對放入temp字典中                                       temp[propertyName]=propertyValue              #調用字典的update函數,把temp中的鍵值對              #添加到 propertyJson字典中              propertyJson.update(temp)              #使用continue,如果為if條件為true則循環執行if語句模塊              continue             else:              #把行號設置為當前行              currentrow=row               #把當前的屬性解碼放入propertyName                        propertyName=currentItem[3].decode("gbk")              #把當前的屬性值解碼放入propertyName              propertyValue=currentItem[4].decode("gbk")              #把serviceId方式字典propertyJson中               propertyJson["serviceId"]=serviceId                #把屬性/值對放入propertyJson字典中               propertyJson[propertyName]=propertyValue              #propertyJsonList.append(propertyJson)               dataList.append(propertyJson)              '''              在這說下:              propertyJson.clear()與propertyJson={}的區別:              propertyJson.clear()是刪除字典的值,不創建引用,會改變字典本身的值;              propertyJson={}是創建新的引用,字典的中的值不發現變化;              如果想讓 self.dataDic.append(propertyJson)該語句執行成功,而且添加每次循環的值,              需要使用propertyJson={}方法;              如果使用propertyJson.clear(),只會把最后一次propertyJson存儲的值,添加到self.dataDic中              '''              propertyJson={}          except Exception,e:            logging.error("Get Property Json Error:"+e)             print "Get Property Json Error:",e      except Exception,e:        logging.error("Get Date Error:"+e)         print "Get Date Error:",e      return dataList       except Exception,e:      logging.error("Reading Data TO Dic Error:"+e)       print "Reading Data TO Dic Error:",e      def getAllServiceId(self):    try:      dataList=self.readDataToList()      serList=[item["serviceId"] for item in dataList if item["serviceId"] ]       serList=list(set(serList))      return serList    except Exception,e:      logging.error("Create ServiceId List Error:"+e)      print "Create ServiceId List Error:"+e                      def oupPutData(self):    try:      dataList=self.readDataToList()      for item in dataList:               print "{"            for key,val in item.items():             print key,":",val          print "}"          print "#"*50    except Exception,e:      logging.error("OutPut Data Error:"+e)      print "OutPut Data Error:"+e       def createDataDic(self):    try:      dataDic={}            dataList=self.readDataToList()      count=0      for item in dataList:        if item["serviceId"]==u"pageview":          count+=1      print count                serviceIdList=self.getAllServiceId()      if len(serviceIdList)>0 and len(dataList)>0:        for serviceId in serviceIdList:          sameServiceidJosnList=[]          for item in dataList:                      itemServiceId=item["serviceId"]            if itemServiceId:              if serviceId==itemServiceId:                 sameServiceidJosnList.append(item)                                           else:              print "ServiceId is null"          dataDic[serviceId]=sameServiceidJosnList                 else:        print "seriviceIdList or dataList is null"      return dataDic      '''       for key,val in dataDic.items():        print key,len(val)        print "*"*50        for item in val:          print "{"          for ke,va in item.items():            print ke,":",va          print "}"        print "-"*50      '''    except Exception,e:      print "Create Data Dictionary Error:",e     def test():  gen =GenExceptData()  gen.oupPutData()  if __name__=="__main__":  test()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桂平市| 康定县| 石林| 牟定县| 杭州市| 伊川县| 房山区| 神木县| 太仆寺旗| 阳泉市| 石首市| 夏津县| 太湖县| 北碚区| 克拉玛依市| 北京市| 绥中县| 辽阳市| 洪泽县| 永济市| 丰镇市| 宁化县| 崇礼县| 碌曲县| 镇巴县| 金沙县| 民权县| 泰顺县| 左权县| 栾城县| 大荔县| 莱阳市| 收藏| 大邑县| 休宁县| 潍坊市| 兰溪市| 中阳县| 双城市| 泉州市| 洪湖市|