您的位置:首页 > 编程语言 > Python开发

Python把csv文件中的信息写入字典中脚本(尝试)

2017-07-07 17:30 573 查看
该段代码,只供参考,与期望不符合,后期会附上,完成的脚本源码

#coding=utf8
import csv
class GenExceptData(object):
def __init__(self):
try:
self.dataDic={}
self.mdbuffer=[]
#打开工作薄
csvHand=open("20170510174450.csv","r")
readcsv=csv.reader(csvHand)
for row in readcsv:
self.mdbuffer.append(row)
#把数据按 按照相应格式写入excel表中
self.readDataToDicl()
#保存文件
except Exception,e:
print "Read Excel error:",e
finally:
csvHand.close()

def readDataToDicl(self):
try:

rowNumber=len(self.mdbuffer)
currentrow=1
propertyJson={}
for row in range(1,rowNumber):
temp={}
item=self.mdbuffer[row]
currentItem=self.mdbuffer[currentrow]
mdEvent= currentItem[0].decode("gbk")
serviceId= currentItem[2].decode("gbk")
propertyName=item[3].decode("gbk")
propertyValue=item[4].decode("gbk")
if item[0]==currentItem[0] and item[2]==currentItem[2]:
print row , currentrow,mdEvent,serviceId,propertyName,propertyValue
temp["serviceId"]=serviceId
temp[propertyName]=propertyValue
propertyJson.update(temp)
temp.clear()
continue
else:
currentrow=row
currentItem=self.mdbuffer[currentrow+1]
mdEvent= currentItem[0].decode("gbk")
serviceId= currentItem[2].decode("gbk")
proName=currentItem[3].decode("gbk")
proValue=currentItem[4].decode("gbk")
temp["serviceId"]=serviceId
temp[proName]=proValue
print row , currentrow,mdEvent,serviceId,propertyName,propertyValue
propertyJson.update(temp)
temp.clear()
continue
break

for key,val in propertyJson.items():
print key,"=",val.encode("utf8")
print "*"*50

self.dataDic[mdEvent]=propertyJson
'''
for value in self.dataDic.values():
for key,val in value.items():
print key,"=",val.encode("utf8")
print "*"*50
'''
except Exception,e:
print "Reading Data TO Dic Error:",e

def test():
GenExceptData()

if __name__=="__main__":
test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: