Python把csv数据写入list和字典类型的变量脚本方法


Posted in Python onJune 15, 2018

如下所示:

#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")
      #创建读取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()

以上这篇Python把csv数据写入list和字典类型的变量脚本方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中用Decorator来简化元编程的教程
Apr 13 Python
Python中title()方法的使用简介
May 20 Python
分析Python中设计模式之Decorator装饰器模式的要点
Mar 02 Python
总结网络IO模型与select模型的Python实例讲解
Jun 27 Python
利用python模拟sql语句对员工表格进行增删改查
Jul 05 Python
Python基于回溯法子集树模板解决取物搭配问题实例
Sep 02 Python
Django实现快速分页的方法实例
Oct 22 Python
对Python3中的input函数详解
Apr 22 Python
python 字符串常用方法汇总详解
Sep 16 Python
3种python调用其他脚本的方法
Jan 06 Python
Python print不能立即打印的解决方式
Feb 19 Python
解决Jupyter NoteBook输出的图表太小看不清问题
Apr 16 Python
Python对象属性自动更新操作示例
Jun 15 #Python
numpy使用fromstring创建矩阵的实例
Jun 15 #Python
详解Python 协程的详细用法使用和例子
Jun 15 #Python
在NumPy中创建空数组/矩阵的方法
Jun 15 #Python
numpy中矩阵合并的实例
Jun 15 #Python
对numpy中shape的深入理解
Jun 15 #Python
Python基于property实现类的特性操作示例
Jun 15 #Python
You might like
广播爱好者需要了解的天线知识
2021/03/01 无线电
德生S2000南麂列岛台湾FM收听记录
2021/03/02 无线电
PHP开发不能违背的安全规则 过滤用户输入
2011/05/01 PHP
php中flush()、ob_flush()、ob_end_flush()的区别介绍
2013/02/17 PHP
ThinkPHP多语言支持与多模板支持概述
2014/08/22 PHP
PHP后门隐藏的一些技巧总结
2020/11/04 PHP
编写可维护面向对象的JavaScript代码[翻译]
2011/02/12 Javascript
js实现绿白相间竖向网页百叶窗动画切换效果
2015/03/02 Javascript
jQuery处理图片加载失败的常用方法
2015/06/08 Javascript
深入浅析JavaScript中对事件的三种监听方式
2015/09/29 Javascript
js如何实现淡入淡出效果
2020/11/18 Javascript
jQuery无刷新上传之uploadify3.1简单使用
2016/06/18 Javascript
JavaScript自学笔记(必看篇)
2016/06/23 Javascript
Bootstrap图片轮播组件Carousel使用方法详解
2016/10/20 Javascript
微信小程序 删除项目工程实现步骤
2016/11/10 Javascript
如何判断出一个js对象是否一个dom对象
2016/11/24 Javascript
jQGrid Table操作列中点击【操作】按钮弹出按钮层的实现代码
2016/12/05 Javascript
原生javascript移动端滑动banner效果
2017/03/10 Javascript
jQuery实现上传图片前预览效果功能
2017/08/03 jQuery
bootstrap paginator分页插件的两种使用方式实例详解
2017/11/14 Javascript
通过vue提供的keep-alive减少对服务器的请求次数
2018/04/01 Javascript
vue treeselect获取当前选中项的label实例
2020/08/31 Javascript
Python使用pyautogui模块实现自动化鼠标和键盘操作示例
2018/09/04 Python
PyQT5 QTableView显示绑定数据的实例详解
2019/06/25 Python
Pytorch提取模型特征向量保存至csv的例子
2020/01/03 Python
Python结合Window计划任务监测邮件的示例代码
2020/08/05 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
2021/01/01 Python
Corelle官方网站:购买康宁餐具
2016/11/02 全球购物
Snapfish爱尔兰:在线照片打印和个性化照片礼品
2018/09/17 全球购物
安全标语大全
2014/06/10 职场文书
领导干部个人对照检查材料(群众路线)
2014/09/26 职场文书
领导欢迎词致辞
2015/01/23 职场文书
2015年妇女工作总结
2015/05/14 职场文书
音乐剧猫观后感
2015/06/04 职场文书
2016年教师学习教师法心得体会
2016/01/20 职场文书
如何让你的Nginx支持分布式追踪详解
2022/07/07 Servers