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之坑爹的字符编码
Sep 28 Python
利用python将pdf输出为txt的实例讲解
Apr 23 Python
python 字典中取值的两种方法小结
Aug 02 Python
GitHub 热门:Python 算法大全,Star 超过 2 万
Apr 29 Python
Python 抓取微信公众号账号信息的方法
Jun 14 Python
使用 Python 合并多个格式一致的 Excel 文件(推荐)
Dec 09 Python
python与mysql数据库交互的实现
Jan 06 Python
Python利用逻辑回归分类实现模板
Feb 15 Python
Python Matplotlib简易教程(小白教程)
Jul 28 Python
Python: glob匹配文件的操作
Dec 11 Python
Python 的 sum() Pythonic 的求和方法详细
Oct 16 Python
Python matplotlib多个子图绘制整合
Apr 13 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静态新闻列表自动生成代码
2007/06/14 PHP
PHP笔记之:日期函数的使用介绍
2013/04/24 PHP
如何利用php array_multisort函数 对数据库结果进行复杂排序
2013/06/08 PHP
PHP图形操作之Jpgraph学习笔记
2015/12/25 PHP
PHP经典算法集锦【经典收藏】
2016/09/14 PHP
基于PHP实现用户注册登录功能
2016/10/14 PHP
php实现微信模拟登陆、获取用户列表及群发消息功能示例
2017/06/28 PHP
php制作圆形用户头像的实例_自定义封装类源代码
2017/09/18 PHP
解决Laravel 不能创建 migration 的问题
2019/10/09 PHP
YII2框架中日志的配置与使用方法实例分析
2020/03/18 PHP
JavaScript 组件之旅(四):测试 JavaScript 组件
2009/10/28 Javascript
jQuery数据缓存功能的实现思路及简单模拟
2013/05/27 Javascript
面向对象继承实例(a如何继承b问题)(自写)
2013/07/01 Javascript
JQuery实现点击div以外的位置隐藏该div窗口
2013/09/13 Javascript
Node调试工具JSHint的安装及配置教程
2014/05/27 Javascript
jQuery实现无限往下滚动效果代码
2016/04/16 Javascript
基于JS实现导航条flash导航条
2016/06/17 Javascript
深入理解javascript作用域第二篇之词法作用域和动态作用域
2016/07/24 Javascript
jQuery实现用户信息表格的添加和删除功能
2017/09/12 jQuery
详解基于iview-ui的导航栏路径(面包屑)配置
2019/02/22 Javascript
[01:04]DOTA2上海特锦赛现场采访 FreeAgain遭众解说围攻
2016/03/25 DOTA
[02:38]DOTA2 夜魇暗潮2020活动介绍官方视频
2020/11/04 DOTA
使用Python的web.py框架实现类似Django的ORM查询的教程
2015/05/02 Python
python3读取excel文件只提取某些行某些列的值方法
2018/07/10 Python
PyTorch 1.0 正式版已经发布了
2018/12/13 Python
Python基础之函数的定义与使用示例
2019/03/23 Python
Django项目中添加ldap登陆认证功能的实现
2019/04/04 Python
Python 分布式缓存之Reids数据类型操作详解
2020/06/24 Python
Python安装Bs4的多种方法
2020/11/28 Python
css3 给背景设置渐变色的方法
2019/09/12 HTML / CSS
新加坡鲜花速递/新加坡网上花店:Ferns N Petals
2020/08/29 全球购物
行政部工作岗位职责范本
2014/03/05 职场文书
教师学期末个人总结
2015/02/13 职场文书
2015年12.4全国法制宣传日活动总结
2015/03/24 职场文书
导游词之青岛太清宫
2019/12/13 职场文书
JavaScript实现班级抽签小程序
2021/05/19 Javascript