12-第1步_读取电子表格数据
第1步:读取电子表格数据
censuspopdata.xlsx
电子表格中只有一张表,名为 'Population by Census Tract'
。每一行都保存了一个普查区的数据。列分别是普查区的编号(A)、州的简称(B)、县的名称(C)、普查区的人口(D)。
打开一个新的文件编辑器窗口,输入以下代码,将文件保存为readCensusExcel.py:
#! python3
# readCensusExcel.py - Tabulates population and number of census tracts for
# each county.
❶ import openpyxl, pprint
print('Opening workbook...')
❷ wb = openpyxl.load_workbook('censuspopdata.xlsx')
❸ sheet = wb['Population by Census Tract']
countyData = {}
# TODO: Fill in countyData with each county's population and tracts.
print('Reading rows...')
❹ for row in range(2, sheet.max_row + 1):
# Each row in the spreadsheet has data for one census tract.
state = sheet['B' + str(row)].value
county = sheet['C' + str(row)].value
pop = sheet['D' + str(row)].value
# TODO: Open a new text file and write the contents of countyData to it.
这段代码导入了 openpyxl
模块,也导入了 pprint
模块,用 pprint
模块来输出最终的县的数据❶。然后代码打开了 censuspopdata.xlsx
文件❷,取得了包含人口普查数据的工作表❸,并开始迭代它的行❹。
请注意,你也创建了一个 countyData
变量,它将包含你计算的每个县的人口和普查区数目。在它里面存储任何数据之前,你应该确定它内部的数据结构。