@@ -0,0 +1,1383 @@
+#! python3%0A# P02_readCensusExcel.py - Tabulates population and number of census tracts for%0A# each county.%0A#%0A# Note:%0A# - The censuspopdata.xlsx workbook can be downloaded from%0A#   https://nostarch.com/automatestuff/%0A%0Aimport openpyxl, pprint%0Aprint(%22Opening workbook...%22)%0Awb = openpyxl.load_workbook(%22censuspopdata.xlsx%22)%0Asheet = wb.get_sheet_by_name(%22Population by Census Tract%22)%0AcountyData = %7B%7D%0A%0A# Fill in countyData with each county's population and tracts.%0Aprint(%22Reading rows...%22)%0Afor row in range(2, sheet.get_highest_row() + 1):%0A    # Each row in the spreadsheet has data for one census tract.%0A    state = sheet%5B'B' + str(row)%5D.value%0A    county = sheet%5B'C' + str(row)%5D.value%0A    pop = sheet%5B'D' + str(row)%5D.value%0A%0A    # Make sure the key for this state exists.%0A    countyData.setdefault(state, %7B%7D)%0A    # Make sure the key for this county in this state exists.%0A    countyData%5Bstate%5D.setdefault(county, %7B%22tracts%22: 0, %22pop%22: 0%7D)%0A%0A    # Each row represents one census tract, so increment by one.%0A    countyData%5Bstate%5D%5Bcounty%5D%5B%22tracts%22%5D += 1%0A    # Increase the county pop by the pop in this census tract.%0A    countyData%5Bstate%5D%5Bcounty%5D%5B%22pop%22%5D += int(pop)%0A%0A# Open a new text file and write the contents of countyData to it.%0Aprint(%22Writing results...%22)%0AresultFile = open(%22census2010.py%22, 'w')%0AresultFile.write(%22allData = %22 + pprint.pformat(countyData))%0AresultFile.close()%0Aprint(%22Done.%22)%0A

Initialize P02_readCensusExcel