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中的分片与截断序列
Aug 09 Python
python3+requests接口自动化session操作方法
Oct 13 Python
解决项目pycharm能运行,在终端却无法运行的问题
Jan 19 Python
python 通过类中一个方法获取另一个方法变量的实例
Jan 22 Python
在Python中用GDAL实现矢量对栅格的切割实例
Mar 11 Python
Python3监控windows,linux系统的CPU、硬盘、内存使用率和各个端口的开启情况详细代码实例
Mar 18 Python
keras 指定程序在某块卡上训练实例
Jun 22 Python
Python 程序报错崩溃后如何倒回到崩溃的位置(推荐)
Jun 23 Python
python 图像插值 最近邻、双线性、双三次实例
Jul 05 Python
解决Python中导入自己写的类,被划红线,但不影响执行的问题
Jul 13 Python
python 6行代码制作月历生成器
Sep 18 Python
Python时间操作之pytz模块使用详解
Jun 14 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
php 8小时时间差的解决方法小结
2009/12/22 PHP
destoon切换城市后实现logo旁边显示地区名称的方法
2014/08/21 PHP
PHP面向对象程序设计实例分析
2016/01/26 PHP
PHP如何实现跨域
2016/05/30 PHP
DIY jquery plugin - tabs标签切换实现代码
2010/12/11 Javascript
js原型链原理看图说明
2012/07/07 Javascript
js输出阴历、阳历、年份、月份、周示例代码
2014/01/29 Javascript
浅谈 javascript 事件处理
2015/01/04 Javascript
JavaScript判断是否为数组的3种方法及效率比较
2015/04/01 Javascript
JavaScript之Object类型介绍
2015/04/01 Javascript
jquery点击缩略图切换视频播放特效代码分享
2015/09/15 Javascript
JQuery通过AJAX从后台获取信息显示在表格上并支持行选中
2015/09/15 Javascript
nodejs 中模拟实现 emmiter 自定义事件
2016/02/22 NodeJs
使用BootStrap实现用户登录界面UI
2016/08/10 Javascript
Bootstrap table两种分页示例
2016/12/23 Javascript
js实现tab选项卡切换功能
2017/01/13 Javascript
js获取隐藏元素的宽高
2017/02/24 Javascript
Bootstrap实现基于carousel.js框架的轮播图效果
2017/05/02 Javascript
vue-axios使用详解
2017/05/10 Javascript
微信小程序点击控件修改样式实例详解
2017/07/07 Javascript
jQuery AJAX与jQuery事件的分析讲解
2019/02/18 jQuery
JavaScript实现图片放大预览效果
2020/11/02 Javascript
[44:47]Ti4 循环赛第三日 iG vs NaVi
2014/07/12 DOTA
[03:11]完美世界DOTA2联赛PWL DAY8集锦
2020/11/09 DOTA
[01:20]PWL S2开团时刻第三期——团战可以输 蝙蝠必须死
2020/11/26 DOTA
[45:52]完美世界DOTA2联赛PWL S3 Forest vs INK ICE 第二场 12.09
2020/12/12 DOTA
用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试
2014/07/14 Python
Python专用方法与迭代机制实例分析
2014/09/15 Python
批处理与python代码混合编程的方法
2016/05/19 Python
python TCP Socket的粘包和分包的处理详解
2018/02/09 Python
python如何拆分含有多种分隔符的字符串
2018/03/20 Python
使用opencv中匹配点对的坐标提取方式
2020/06/04 Python
生产部厂长职位说明书
2014/03/03 职场文书
2014教师年度思想工作总结
2014/11/10 职场文书
工程合作意向书范本
2015/05/09 职场文书
新学期家长寄语2016
2015/12/03 职场文书