Skip to content

Instantly share code, notes, and snippets.

@nblmc
Created September 30, 2020 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblmc/acb458112907370a7b8877e3c5af63ee to your computer and use it in GitHub Desktop.
Save nblmc/acb458112907370a7b8877e3c5af63ee to your computer and use it in GitHub Desktop.
Python census puller

Python Census variable puller for Massachusetts data

./census-puller.py {{UNIT}} {{CENSUSVARS}}

#/usr/bin/env python3
import requests
import csv
import argparse
parser = argparse.ArgumentParser(description="Pull down data from Census variables")
parser.add_argument('unit')
parser.add_argument('censusvars')
args = parser.parse_args()
outfile = '{}.csv'.format(args.censusvars)
# This is the API endpoint for 2018 ACS 5 year data
url = 'https://api.census.gov/data/2018/acs/acs5?get=NAME,{}&for={}:*&in=state:25'.format(args.censusvars, args.unit)
print(url)
req = requests.get(url)
raw = req.json()
print (raw)
raw[0].append('geoid')
for index, row in enumerate(raw):
if index > 0:
raw[index].append('{}{}{}'.format(row[-3],row[-2],row[-1]) )
with open(outfile, 'w') as out:
writer = csv.writer(out)
writer.writerows(raw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment