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字符串和字典
Jul 07 Python
python django事务transaction源码分析详解
Mar 17 Python
django中静态文件配置static的方法
May 20 Python
python变量的存储原理详解
Jul 10 Python
python 使用装饰器并记录log的示例代码
Jul 12 Python
基于Django框架的权限组件rbac实例讲解
Aug 31 Python
django-crontab 定时执行任务方法的实现
Sep 06 Python
python中web框架的自定义创建
Sep 08 Python
python实现俄罗斯方块小游戏
Apr 24 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
Jan 01 Python
python编写扎金花小程序的实例代码
Feb 23 Python
django如何自定义manage.py管理命令
Apr 27 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统计目录下的文件总数及代码行数(去除注释及空行)
2011/01/17 PHP
php三维数组去重(示例代码)
2013/11/26 PHP
Ubuntu server 11.04安装memcache及php使用memcache来存储session的方法
2016/05/31 PHP
Bootstrap+PHP实现多图上传功能实例详解
2018/04/08 PHP
如何使用Jquery获取Form表单中被选中的radio值
2013/08/09 Javascript
ajax与302响应代码测试
2013/10/23 Javascript
jQuery删除节点的三个方法即remove()detach()和empty()
2013/12/27 Javascript
js实现俄罗斯方块小游戏分享
2014/01/31 Javascript
Javascript判断文件是否存在(客户端/服务器端)
2014/09/16 Javascript
jquery实现增加删除行的方法
2015/02/03 Javascript
jQuery中slideUp 和 slideDown 的点击事件
2015/02/26 Javascript
jquery+html仿翻页相册功能
2016/12/20 Javascript
微信小程序 开发之顶部导航栏实例代码
2017/02/23 Javascript
利用node.js+mongodb如何搭建一个简单登录注册的功能详解
2017/07/30 Javascript
关于Webpack dev server热加载失败的解决方法
2018/02/22 Javascript
webpack4 css打包压缩问题的解决
2018/05/18 Javascript
详解NodeJs开发微信公众号
2018/05/25 NodeJs
JS几个常用的函数和对象定义与用法示例
2020/01/15 Javascript
Vue实现 点击显示再点击隐藏效果(点击页面空白区域也隐藏效果)
2020/01/16 Javascript
vue 添加和编辑用同一个表单,el-form表单提交后清空表单数据操作
2020/08/03 Javascript
python中self原理实例分析
2015/04/30 Python
python创建进程fork用法
2015/06/04 Python
实例讲解Python中global语句下全局变量的值的修改
2016/06/16 Python
Python获取当前函数名称方法实例分享
2018/01/18 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
2018/02/26 Python
Python 、Pycharm、Anaconda三者的区别与联系、安装过程及注意事项
2019/10/11 Python
django序列化serializers过程解析
2019/12/14 Python
pytorch+lstm实现的pos示例
2020/01/14 Python
python 解压、复制、删除 文件的实例代码
2020/02/26 Python
美国大城市最热门旅游景点门票:CityPASS
2016/12/16 全球购物
澳大利亚优惠网站:Deals.com.au
2019/07/02 全球购物
法院实习人员自我鉴定
2013/09/26 职场文书
个人简历中的自我评价怎么写
2014/01/26 职场文书
卫校毕业生个人自我鉴定
2014/04/28 职场文书
道歉信怎么写
2015/05/12 职场文书
Java如何实现通过键盘输入一个数组
2022/02/15 Java/Android