Python把csv數(shù)據(jù)寫入list和字典類型的變量腳本方法
更新時間:2018年06月15日 16:13:20 作者:壞蛋是我
今天小編就為大家分享一篇Python把csv數(shù)據(jù)寫入list和字典類型的變量腳本方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
如下所示:
#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')
'''
該模塊的主要功能,是根據(jù)已有的csv文件,
通過readDataToDicl函數(shù),把csv中對應(yīng)的部分,
寫入字典中,每個字典當(dāng)當(dāng)作一條json數(shù)據(jù)
'''
class GenExceptData(object):
def __init__(self):
try:
#存放csv中讀取的數(shù)據(jù)
self.mdbuffer=[]
#打開csv文件,設(shè)置讀的權(quán)限
csvHand=open("20170510174450.csv","r")
#創(chuàng)建讀取csv文件句柄
readcsv=csv.reader(csvHand)
#把csv的數(shù)據(jù)讀取到mdbuffer中
for row in readcsv:
self.mdbuffer.append(row)
#把數(shù)據(jù)穿件為為字典類型的
#self.readDataToList()
#保存文件
except Exception,e:
logging.error("Read Excel error:"+e)
finally:
#關(guān)閉csv文件
csvHand.close()
def readDataToList(self):
try:
#獲取mdbuffer中的元素個數(shù)
rowNumber=len(self.mdbuffer)
#設(shè)置當(dāng)前行號
currentrow=1
#設(shè)置json數(shù)據(jù)的屬性值
propertyJson={}
#propertyJsonList=[]
#count=0
#讀取列表中的元素
dataList=[]
try:
for row in range(1,rowNumber):
#創(chuàng)建一個臨時變量用來存取一次循環(huán)的屬性鍵值
temp={}
#獲取列表中一個元素
item=self.mdbuffer[row]
#獲取當(dāng)前元素,當(dāng)前元素代表的是每個
#事件起始的位置
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
#調(diào)用字典的update函數(shù),把temp中的鍵值對
#添加到 propertyJson字典中
propertyJson.update(temp)
#使用continue,如果為if條件為true則循環(huán)執(zhí)行if語句模塊
continue
else:
#把行號設(shè)置為當(dāng)前行
currentrow=row
#把當(dāng)前的屬性解碼放入propertyName
propertyName=currentItem[3].decode("gbk")
#把當(dāng)前的屬性值解碼放入propertyName
propertyValue=currentItem[4].decode("gbk")
#把serviceId方式字典propertyJson中
propertyJson["serviceId"]=serviceId
#把屬性/值對放入propertyJson字典中
propertyJson[propertyName]=propertyValue
#propertyJsonList.append(propertyJson)
dataList.append(propertyJson)
'''
在這說下:
propertyJson.clear()與propertyJson={}的區(qū)別:
propertyJson.clear()是刪除字典的值,不創(chuàng)建引用,會改變字典本身的值;
propertyJson={}是創(chuàng)建新的引用,字典的中的值不發(fā)現(xiàn)變化;
如果想讓 self.dataDic.append(propertyJson)該語句執(zhí)行成功,而且添加每次循環(huán)的值,
需要使用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數(shù)據(jù)寫入list和字典類型的變量腳本方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python簡單實現(xiàn)網(wǎng)頁內(nèi)容抓取功能示例
這篇文章主要介紹了Python簡單實現(xiàn)網(wǎng)頁內(nèi)容抓取功能,結(jié)合實例形式分析了Python基于urllib模塊的網(wǎng)頁請求、內(nèi)容讀取等相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
python中數(shù)字列表轉(zhuǎn)化為數(shù)字字符串的實例代碼
先前學(xué)習(xí)過,數(shù)字和字符串都可以存儲到變量當(dāng)中,下面這篇文章主要給大家介紹了關(guān)于python中數(shù)字列表轉(zhuǎn)化為數(shù)字字符串的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
python線程鎖(thread)學(xué)習(xí)示例
python thread提供了低級別的、原始的線程以及一個簡單的鎖,下面提供一個python線程線程鎖(thread)學(xué)習(xí)示例,大家參考使用2013-12-12
3個Python?SQLAlchemy數(shù)據(jù)庫操作功能詳解
Python?SQLAlchemy?是一個強大且多功能的?Python?SQL?工具包和對象關(guān)系映射?(ORM)?系統(tǒng),提供了一整套眾所周知的企業(yè)級持久性模式,本文為大家整理了它必須了解的3個數(shù)據(jù)庫操作功能,希望對大家有所幫助2023-09-09

