欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

如下所示:

#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')
'''
該模塊的主要功能,是根據已有的csv文件,
通過readDataToDicl函數,把csv中對應的部分,
寫入字典中,每個字典當當作一條json數據
'''
class GenExceptData(object):
  def __init__(self):
    try:
      #存放csv中讀取的數據
      self.mdbuffer=[]
      #打開csv文件,設置讀的權限
      csvHand=open("20170510174450.csv","r")
      #創(chuàng)建讀取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):
          #創(chuàng)建一個臨時變量用來存取一次循環(huán)的屬性鍵值
          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則循環(huán)執(zhí)行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={}的區(qū)別:
              propertyJson.clear()是刪除字典的值,不創(chuàng)建引用,會改變字典本身的值;
              propertyJson={}是創(chuàng)建新的引用,字典的中的值不發(fā)現變化;
              如果想讓 self.dataDic.append(propertyJson)該語句執(zhí)行成功,而且添加每次循環(huán)的值,
              需要使用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()

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

相關文章

  • Python簡單實現網頁內容抓取功能示例

    Python簡單實現網頁內容抓取功能示例

    這篇文章主要介紹了Python簡單實現網頁內容抓取功能,結合實例形式分析了Python基于urllib模塊的網頁請求、內容讀取等相關操作技巧,需要的朋友可以參考下
    2018-06-06
  • python中數字列表轉化為數字字符串的實例代碼

    python中數字列表轉化為數字字符串的實例代碼

    先前學習過,數字和字符串都可以存儲到變量當中,下面這篇文章主要給大家介紹了關于python中數字列表轉化為數字字符串的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-02-02
  • Python logging模塊handlers用法詳解

    Python logging模塊handlers用法詳解

    這篇文章主要介紹了Python logging模塊handlers用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • Python異常處理操作實例詳解

    Python異常處理操作實例詳解

    這篇文章主要介紹了Python異常處理操作,結合實例形式分析了Python常見的異常處理類型、相關操作技巧與注意事項,需要的朋友可以參考下
    2018-08-08
  • python線程鎖(thread)學習示例

    python線程鎖(thread)學習示例

    python thread提供了低級別的、原始的線程以及一個簡單的鎖,下面提供一個python線程線程鎖(thread)學習示例,大家參考使用
    2013-12-12
  • 淺談一下python線程池簡單應用

    淺談一下python線程池簡單應用

    這篇文章主要介紹了淺談一下python線程池簡單應用,線程池在系統(tǒng)啟動時即創(chuàng)建大量空閑的線程,程序只要將一個函數提交給線程池,線程池就會啟動一個空閑的線程來執(zhí)行它,需要的朋友可以參考下
    2023-04-04
  • 3個Python?SQLAlchemy數據庫操作功能詳解

    3個Python?SQLAlchemy數據庫操作功能詳解

    Python?SQLAlchemy?是一個強大且多功能的?Python?SQL?工具包和對象關系映射?(ORM)?系統(tǒng),提供了一整套眾所周知的企業(yè)級持久性模式,本文為大家整理了它必須了解的3個數據庫操作功能,希望對大家有所幫助
    2023-09-09
  • opencv實現圖像校正

    opencv實現圖像校正

    這篇文章主要為大家詳細介紹了opencv實現圖像校正,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • Python處理時間戳和時間計算等的腳本分享

    Python處理時間戳和時間計算等的腳本分享

    這篇文章主要為大家整理總結了5個實用的Python小,可以實現時間戳處理和時間計算。文中的示例代碼講解詳細,感興趣的小伙伴可以學習一下
    2022-07-07
  • python列表的增刪改查實例代碼

    python列表的增刪改查實例代碼

    下面小編就為大家分享一篇python列表的增刪改查實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01

最新評論