python调用excel数据转换成dict_python Excel解析成Dict格式

#-*- coding: utf-8 -*-

importos#存放配置文件目录

filePath = os.path.join(os.path.dirname(__file__), 'pyConfig')#文件名

fileName = "pyInfo.txt"

## 解析Excel# ## None

classReadPySlx():## 初始化

#@parma beginLine 数据从哪一行开始有效

#@parma fileName 目标文件名

## return None

def __init__(self, beginLine, fileName):

self.beginLine= beginLine #正文开始的行数

self.fileName = fileName #文件名

self.headNameList = [] #字段头列表

self.headCnt = 0 #字段头的数量

self.contentDict = {} #最后保存的字典

## 读目标文件

#@parma None Null

## return None

defreadFile(self):

tagFile= open(self.fileName, 'rb')#逐行读文件

for index, lineInfo inenumerate(tagFile):if len(lineInfo.strip()) <=0:break

#不是头文件并且还没到正文

if index < self.beginLine and index !=0:continuelineList= lineInfo.strip().split('\t')

lineCnt=len(lineList)#空行

if lineCnt <=0:break

#是字段头

if index ==0:

self.headNameList=lineList

self.headCnt=lineCntcontinue

#字段错误,和字段头不对应

if lineCnt !=self.headCnt:print "##line cnt error, index=%s"%indexbreak

#添加到字典

self.explainList(lineList)

tagFile.close()return

## 解析成字典

#@parma lineList 每行字段值的列表

## return None

defexplainList(self, lineList):

lineDict={}

tagLineDict={}for i inrange(self.headCnt):

lineDict[self.headNameList[i]]=lineList[i]

tagLineDict[lineList[0]]=lineDict

self.contentDict.update(tagLineDict)return

#------------------------------------------------------------

FilePath =os.path.join(filePath, fileName)

a= ReadPySlx(2, FilePath)

a.readFile()printa.contentDict#------------原Excel文件保存为txt-----------------#playerId addGold addExp#玩家id 增加金子数 增加经验数#10000 100 200#10001 101 201#10002 102 202#10003 103 203#10004 104 204#10005 105 205#10006 106 206

#---------------------解析后生成的字典-----------------------------#{#'10004': {'playerId': '10004', 'addExp': '204', 'addGold': '104'},#'10005': {'playerId': '10005', 'addExp': '205', 'addGold': '105'},#'10006': {'playerId': '10006', 'addExp': '206', 'addGold': '106'},#'10000': {'playerId': '10000', 'addExp': '200', 'addGold': '100'},#'10001': {'playerId': '10001', 'addExp': '201', 'addGold': '101'},#'10002': {'playerId': '10002', 'addExp': '202', 'addGold': '102'},#'10003': {'playerId': '10003', 'addExp': '203', 'addGold': '103'},#}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值