最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2018年06月15日 16:13:20   作者:壞蛋是我  
今天小編就為大家分享一篇Python把csv數(shù)據(jù)寫入list和字典類型的變量腳本方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

如下所示:

#coding=utf8
import csv 
import logging
logging.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')
'''
該模塊的主要功能,是根據(jù)已有的csv文件,
通過readDataToDicl函數(shù),把csv中對(duì)應(yīng)的部分,
寫入字典中,每個(gè)字典當(dāng)當(dāng)作一條json數(shù)據(jù)
'''
class GenExceptData(object):
  def __init__(self):
    try:
      #存放csv中讀取的數(shù)據(jù)
      self.mdbuffer=[]
      #打開csv文件,設(shè)置讀的權(quán)限
      csvHand=open("20170510174450.csv","r")
      #創(chuàng)建讀取csv文件句柄
      readcsv=csv.reader(csvHand)
      #把csv的數(shù)據(jù)讀取到mdbuffer中
      for row in readcsv:
          self.mdbuffer.append(row) 
      #把數(shù)據(jù)穿件為為字典類型的
      #self.readDataToList()
      #保存文件
    except Exception,e:
      logging.error("Read Excel error:"+e) 
    finally:
      #關(guān)閉csv文件
      csvHand.close()
 
  def readDataToList(self):
    try:
      #獲取mdbuffer中的元素個(gè)數(shù)
      rowNumber=len(self.mdbuffer)
      #設(shè)置當(dāng)前行號(hào)
      currentrow=1
      #設(shè)置json數(shù)據(jù)的屬性值
      propertyJson={}
      #propertyJsonList=[]
      #count=0
      #讀取列表中的元素  
      dataList=[] 
      try: 
        for row in range(1,rowNumber):
          #創(chuàng)建一個(gè)臨時(shí)變量用來存取一次循環(huán)的屬性鍵值
          temp={}
          
          #獲取列表中一個(gè)元素
          item=self.mdbuffer[row]
          #獲取當(dāng)前元素,當(dāng)前元素代表的是每個(gè)
          #事件起始的位置
          currentItem=self.mdbuffer[currentrow]
          #獲取serviceId并進(jìn)行解碼
          serviceId= currentItem[2].decode("gbk")
          #獲取屬性并進(jìn)行解碼,把解碼的值存入propertyName
          propertyName=item[3].decode("gbk")
          #獲取屬性值并進(jìn)行解碼,把解碼的值存入propertyValue
          propertyValue=item[4].decode("gbk")
          try:
            #判斷埋點(diǎn)事件與serviceId是否相等
            if item[0]==currentItem[0] and item[2]==currentItem[2]:
              #把serviceId方式字典propertyJson中
              propertyJson["serviceId"]=serviceId 
              #把屬性/值對(duì)放入temp字典中                         
              temp[propertyName]=propertyValue
              #調(diào)用字典的update函數(shù),把temp中的鍵值對(duì)
              #添加到 propertyJson字典中
              propertyJson.update(temp)
              #使用continue,如果為if條件為true則循環(huán)執(zhí)行if語句模塊
              continue 
            else:
              #把行號(hào)設(shè)置為當(dāng)前行
              currentrow=row 
              #把當(dāng)前的屬性解碼放入propertyName          
              propertyName=currentItem[3].decode("gbk")
              #把當(dāng)前的屬性值解碼放入propertyName
              propertyValue=currentItem[4].decode("gbk")
              #把serviceId方式字典propertyJson中 
              propertyJson["serviceId"]=serviceId  
              #把屬性/值對(duì)放入propertyJson字典中 
              propertyJson[propertyName]=propertyValue
              #propertyJsonList.append(propertyJson) 
              dataList.append(propertyJson)
              '''
              在這說下:
              propertyJson.clear()與propertyJson={}的區(qū)別:
              propertyJson.clear()是刪除字典的值,不創(chuàng)建引用,會(huì)改變字典本身的值;
              propertyJson={}是創(chuàng)建新的引用,字典的中的值不發(fā)現(xiàn)變化;
              如果想讓 self.dataDic.append(propertyJson)該語句執(zhí)行成功,而且添加每次循環(huán)的值,
              需要使用propertyJson={}方法;
              如果使用propertyJson.clear(),只會(huì)把最后一次propertyJson存儲(chǔ)的值,添加到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()

以上這篇Python把csv數(shù)據(jù)寫入list和字典類型的變量腳本方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

翁源县| 且末县| 秦皇岛市| 迁安市| 滨州市| 正宁县| 阳曲县| 宣武区| 山东省| 监利县| 阿勒泰市| 五大连池市| 封开县| 乐都县| 松溪县| 平舆县| 宝丰县| 常德市| 青岛市| 台中县| 东方市| 汶上县| 花莲县| 新龙县| 延寿县| 阿尔山市| 明溪县| 舒兰市| 彭州市| 昌图县| 星子县| 哈巴河县| 台东市| 鄂托克前旗| 葫芦岛市| 大连市| 虎林市| 额济纳旗| 凌源市| 军事| 永济市|