如下所示:
#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和字典類型的變量腳本方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。