Skip to content

Instantly share code, notes, and snippets.

@vrendina
Created April 22, 2017 19:00
Show Gist options
  • Save vrendina/390a52f8a4696c43e4ef1d6e96428407 to your computer and use it in GitHub Desktop.
Save vrendina/390a52f8a4696c43e4ef1d6e96428407 to your computer and use it in GitHub Desktop.
Validate CSV list of addresses
#!/usr/local/bin/python3
#
# verify.py <input.csv> [<output.csv>]
#
# Validate list of addresses and write output to CSV file
#
# Format of input CSV file should be:
# Name,Address 1,Address 2,City,State,Zip
#
# Format of output CSV file is (unmodified address is written first):
# Name,Address 1,Address 2,City,State,Zip,,Address 1,Address 2,City,State,Zip
#
# Any error messages are written in the Address 1 column of the output
import csv
import sys
import requests
import json
url = 'https://api.lob.com/v1/verify'
key = 'test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc'
skipFirstLine = True
try:
sys.argv[1]
except IndexError:
print("Usage: verify.py input.csv [<output.csv>]")
sys.exit()
inputFile = sys.argv[1]
outputFile = 'output.csv'
try:
outputFile = sys.argv[2]
except IndexError:
pass
csvInput = csv.reader(open(inputFile, 'rU'))
csvOutput = open(outputFile, 'w')
header = 'Name,Address 1,Address 2,City,State,Zip,,Address 1,Address 2,City,State,Zip\n'
csvOutput.write(header)
print('-'*80)
print('Running address validation on ' + sys.argv[1])
print('-'*80)
errorCount = 0
missingCount = 0
for idx, row in enumerate(csvInput):
if skipFirstLine and idx == 0:
continue
name = row[0]
address_line1 = row[1]
address_line2 = row[2]
address_city = row[3]
address_state = row[4]
address_zip = row[5]
payload = { 'address_line1': address_line1,
'address_line2': address_line2,
'address_city': address_city,
'address_state': address_state,
'address_zip': address_zip,
'address_country': 'US'}
output = name + ',' + address_line1 + ',' + address_line2 + ',' + address_city + ',' + address_state + ',' + address_zip + ',,'
print('Checking address for ' + name + '... ', end='')
# Don't actually run the request if we don't have data yet in our file
if not address_line1:
errorMsg = 'no address to check'
output += errorMsg
missingCount+=1
print(errorMsg)
else:
res = requests.post(url, data=payload, auth=(key, ''))
data = json.loads(res.text)
if 'error' in data:
errorMsg = data['error']['message']
output += errorMsg
errorCount+=1
print(errorMsg)
else:
output += data['address']['address_line1'] + ','
output += data['address']['address_line2'] + ','
output += data['address']['address_city'] + ','
output += data['address']['address_state'] + ','
output += data['address']['address_zip']
print('okay')
csvOutput.write(output + '\n')
print('-'*80)
print('Number of errors: ' + str(errorCount) + ' Number of missing: ' + str(missingCount))
print('-'*80)
csvOutput.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment