python excel:2

新建一个Excel文件(瞎编):population.xlsx,并进行读取等相关操作
在这里插入图片描述

'''
一些补充:
excel---->workbook---->worksheet---->(row,column,cell)
'''
import openpyxl
import pprint #打印数据的模块,美观打印数据
#读取出来的数据用字典数据结构存储
'''
数据结构核心:

{'中国':{'北京':{'score2':3,'socre1':189}, #把score相加
         '上海':{....................}},
 
 '美国':{ .......................}

 '日本':{ .......................}
}
'''
print('打开读取excel文件')
wb=openpyxl.load_workbook('population.xlsx')
sheet=wb.active

data={} #输出的数据

'''
setdefault:字典类型的方法函数
picnic={'apple':5,'cup':10}
picnic.setdefault('orange',12) #picnic={'apple':5,'cup':10,'orange',12}

#如果有字典中本来有apple,则会忽略25这个缺省值,不会改变
picnic.setdefault('apple',25)  #picnic={'apple':5,'cup':10,'orange',12}
'''

#遍历表单
for per_row in range(2,sheet.max_row+1):#第一行为头,没有数据,+1是因为range是左闭右开的
    country=sheet['A'+str(per_row)].value  #str(per_row)将其转换为字符串,进行字符串相加
    city=sheet['B'+str(per_row)].value
    score1=sheet['C'+str(per_row)].value
    score2=sheet['D'+str(per_row)].value
    x=score1
    y=score2
    data.setdefault(country,{}) #保证country的值存在

    #下面的'score1' 'socre2'是字符串,与上面的score1 socre2不同
    data[country].setdefault(city,{'score1':0,'socre2':0}) #{score1:0,socre2:0}与前一句的{}类似,还为两个值赋了初值0,方便后面的相加
    data[country][city]['score1']+=int(score1) #累加过程,要使用int类型装换
    data[country][city]['socre2']+=int(score2)
    
print(data)
'''
{'中国': {'北京': {'score1': 189, 'socre2': 3}, '上海': {'score1': 190, 'socre2': 7}},
'美国': {'WT.DC': {'score1': 183, 'socre2': 11}, 'NY': {'score1': 191, 'socre2': 15}},
'日本': {'TK': {'score1': 189, 'socre2': 19}, '大阪': {'score1': 178, 'socre2': 23}}}
'''

#将数据写入文本
print('Writing result.....')
resultfile=open('theresult.py','w') #保存到了一个.py的文件里面,也可以放到word(.doc)或excel(.xlsx)文件里面
'''
使用.py文件可以方便调用。
import resultfile
print(resultfile.allData['中国']['北京']['socre2'])
'''

resultfile.write('the result ='+ pprint.pformat(data)) #pprint.pformat(data):将其输出为字符串
'''
the result ={'中国': {'上海': {'score1': 190, 'socre2': 7}, '北京': {'score1': 189, 'socre2': 3}},
 '日本': {'TK': {'score1': 189, 'socre2': 19},
        '大阪': {'score1': 178, 'socre2': 23}},
 '美国': {'NY': {'score1': 191, 'socre2': 15},
        'WT.DC': {'score1': 183, 'socre2': 11}}}
'''

resultfile.close() #之前没有关闭这个语句,文件始终为空,排查后发现是没有关闭文件的语句


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值