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列表计数及插入实例
Dec 17 Python
Python中index()和seek()的用法(详解)
Apr 27 Python
Python单元测试实例详解
May 25 Python
python使用PIL和matplotlib获取图片像素点并合并解析
Sep 10 Python
Mac 使用python3的matplot画图不显示的解决
Nov 23 Python
Python timeit模块的使用实践
Jan 13 Python
40行Python代码实现天气预报和每日鸡汤推送功能
Feb 27 Python
Python手动或自动协程操作方法解析
Jun 22 Python
Python制作数据预测集成工具(值得收藏)
Aug 21 Python
python+selenium实现12306模拟登录的步骤
Jan 21 Python
Python使用tkinter实现小时钟效果
Feb 22 Python
详解python的xlwings库读写excel操作总结
Feb 26 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
博士208HAF收音机实习报告
2021/03/02 无线电
PHP SQLite类
2009/05/07 PHP
PHP函数preg_match_all正则表达式的基本使用详细解析
2013/08/31 PHP
PHP判断文章里是否有图片的简单方法
2014/07/26 PHP
php在线解压ZIP文件的方法
2014/12/30 PHP
WordPress中设置Post Type自定义文章类型的实例教程
2016/05/10 PHP
php使用file函数、fseek函数读取大文件效率对比分析
2016/11/04 PHP
Laravel 中使用 Vue.js 实现基于 Ajax 的表单提交错误验证操作
2017/06/30 PHP
小程序微信退款功能实现方法详解【基于thinkPHP】
2019/05/05 PHP
php设计模式之抽象工厂模式分析【星际争霸游戏案例】
2020/01/23 PHP
jQuery 渐变下拉菜单
2009/12/15 Javascript
网页加载时页面显示进度条加载完成之后显示网页内容
2012/12/23 Javascript
jQuery实现类似老虎机滚动抽奖效果
2015/08/06 Javascript
详解WordPress开发中get_current_screen()函数的使用
2016/01/11 Javascript
jQuery页面弹出框实现文件上传
2017/02/09 Javascript
angularJS模态框$modal实例代码
2017/05/27 Javascript
vuex2中使用mapGetters/mapActions报错的解决方法
2018/10/20 Javascript
JS数组求和的常用方法总结【5种方法】
2019/01/14 Javascript
JS对象和字符串之间互换操作实例分析
2019/02/02 Javascript
extract-text-webpack-plugin用法详解
2019/02/14 Javascript
layui多图上传实现删除功能的例子
2019/09/23 Javascript
[55:18]Liquid vs Chaos 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
Python实现加载及解析properties配置文件的方法
2018/03/29 Python
python使用Paramiko模块实现远程文件拷贝
2019/04/30 Python
Django admin 实现search_fields精确查询实例
2020/03/30 Python
Python devel安装失败问题解决方案
2020/06/09 Python
html5响应式开发自动计算fontSize的方法
2020/01/13 HTML / CSS
eBay奥地利站:eBay.at
2019/07/24 全球购物
Linux面试题LINUX系统类
2014/11/19 面试题
文秘专业毕业生就业推荐信
2013/11/08 职场文书
新领导上任欢迎词
2014/01/13 职场文书
集团薪酬管理制度
2014/01/13 职场文书
机械设计及其自动化求职推荐信
2014/02/17 职场文书
党风廉政承诺书
2014/03/27 职场文书
银行自荐信范文
2015/03/25 职场文书
2015年超市工作总结范文
2015/05/26 职场文书