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 相关文章推荐
17个Python小技巧分享
Jan 23 Python
python创建临时文件夹的方法
Jul 06 Python
Python 常用的安装Module方式汇总
May 06 Python
python实现rsa加密实例详解
Jul 19 Python
Pandas 对Dataframe结构排序的实现方法
Apr 10 Python
Selenium元素的常用操作方法分析
Aug 10 Python
PyQt5笔记之弹出窗口大全
Jun 20 Python
使用Python opencv实现视频与图片的相互转换
Jul 08 Python
DJANGO-URL反向解析REVERSE实例讲解
Oct 25 Python
python中Ansible模块的Playbook的具体使用
May 28 Python
windows下python 3.9 Numpy scipy和matlabplot的安装教程详解
Nov 28 Python
filter使用python3代码进行迭代元素的实例详解
Dec 03 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使用ffmpeg向视频中添加文字字幕的实现方法
2016/05/23 PHP
php socket通信简单实现
2016/11/18 PHP
PHP获取php,mysql,apche的版本信息及更多服务器信息
2021/03/09 PHP
ExtJS4 Grid改变单元格背景颜色及Column render学习
2013/02/06 Javascript
js导入导出excel(实例代码)
2013/11/25 Javascript
JS打字效果的动态菜单代码分享
2015/08/21 Javascript
JavaScript中的各种操作符使用总结
2016/05/26 Javascript
第五篇Bootstrap 排版
2016/06/21 Javascript
jQuery flip插件实现的翻牌效果示例【附demo源码下载】
2016/09/20 Javascript
Vue + Webpack + Vue-loader学习教程之功能介绍篇
2017/03/14 Javascript
nodejs微信扫码支付功能实现
2018/02/17 NodeJs
判断JavaScript中的两个变量是否相等的操作符
2019/12/21 Javascript
[53:52]OG vs EG 2018国际邀请赛淘汰赛BO3 第二场 8.23
2018/08/24 DOTA
[34:41]夜魇凡尔赛茶话会 第二期02:你画我猜
2021/03/11 DOTA
使用Python编写一个在Linux下实现截图分享的脚本的教程
2015/04/24 Python
python基础知识小结之集合
2015/11/25 Python
Python自定义进程池实例分析【生产者、消费者模型问题】
2016/09/19 Python
Python探索之ModelForm代码详解
2017/10/26 Python
基于Python实现的ID3决策树功能示例
2018/01/02 Python
一文带你了解Python中的字符串是什么
2018/11/20 Python
详解Python 循环嵌套
2020/07/09 Python
css3与html5实现响应式导航菜单(导航栏)效果分享
2014/02/12 HTML / CSS
采购类个人求职的自我评价
2014/02/18 职场文书
幼儿园元旦家长感言
2014/02/27 职场文书
移风易俗倡议书
2014/04/15 职场文书
共产党员公开承诺践诺书
2014/05/28 职场文书
财务管理专业毕业生求职信
2014/06/02 职场文书
检讨书范文500字
2015/01/28 职场文书
写给媳妇的检讨书
2015/05/06 职场文书
经营场所使用证明
2015/06/19 职场文书
python基础入门之普通操作与函数(三)
2021/06/13 Python
Python实现生活常识解答机器人
2021/06/28 Python
Spring依赖注入多种类型数据的示例代码
2022/03/31 Java/Android
关于vue-router-link选择样式设置
2022/04/30 Vue.js
解决Springboot PostMapping无法获取数据的问题
2022/05/06 Java/Android
ubuntu开机后ROS程序自启动问题
2022/12/24 Servers