Created
January 7, 2015 02:38
-
-
Save cdlewis/e59ef2fd3f21b9455856 to your computer and use it in GitHub Desktop.
Classifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import csv | |
import urllib | |
if len( sys.argv ) < 4: | |
print "Error: incorrect number of arguments." | |
print "Usage: %s <key> <input file> <output file>" % sys.argv[ 0 ] | |
key = sys.argv[ 1 ] | |
input_file = sys.argv[ 2 ] | |
output_file = sys.argv[ 3 ] | |
reader = csv.DictReader( open( input_file, 'r' ) ) | |
with open( output_file, 'w' ) as output: | |
fields = list( set( reader.fieldnames + [ 'Zip' ] ) ) | |
writer = csv.DictWriter( output, fields ) | |
writer.writeheader() | |
for row in list( reader )[ ::-1 ]: | |
if not row.has_key( 'Zip' ) or row[ 'Zip' ] != '': | |
try: | |
zipcode = urllib.urlopen( 'http://ipinfo.io/%s/postal?token=%s' % ( row[ 'User IP' ], key ) ).read() | |
row[ 'Zip' ] = zipcode.strip( '\n' ) | |
print row | |
except: | |
print 'Error: unable to open URL' | |
zipcode = "" | |
writer.writerow( row ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment