|
| 1 | +import csv |
| 2 | +import requests |
| 3 | + |
| 4 | + |
| 5 | +def get_addresses(filename): |
| 6 | + """ |
| 7 | + Given a CSV file, this function returns a list of lists |
| 8 | + where each element (list) in the outer list contains the |
| 9 | + row info from the csv file. |
| 10 | + """ |
| 11 | + all_addresses = [] |
| 12 | + with open(filename, 'rb') as f: |
| 13 | + reader = csv.reader(f) |
| 14 | + for row in reader: |
| 15 | + all_addresses.append(row) |
| 16 | + return all_addresses |
| 17 | + |
| 18 | + |
| 19 | +def get_geolocation(all_the_ip_address): |
| 20 | + """ |
| 21 | + Given a list of lists from `get_addresses()`, this function |
| 22 | + returns an updated lists of lists containing the geolocation. |
| 23 | + """ |
| 24 | + print("Getting geo information...") |
| 25 | + updated_addresses = [] |
| 26 | + counter = 1 |
| 27 | + # update header |
| 28 | + header_row = all_the_ip_address.pop(0) |
| 29 | + header_row.extend(['Country', 'City']) |
| 30 | + # get geolocation |
| 31 | + for line in all_the_ip_address: |
| 32 | + print "Grabbing geo info for row # {0}".format(counter) |
| 33 | + r = requests.get('https://freegeoip.net/json/{0}'.format(line[0])) |
| 34 | + line.extend([str(r.json()['country_name']), str(r.json()['city'])]) |
| 35 | + updated_addresses.append(line) |
| 36 | + counter += 1 |
| 37 | + updated_addresses.insert(0, header_row) |
| 38 | + return updated_addresses |
| 39 | + |
| 40 | + |
| 41 | +def create_csv(updated_address_list): |
| 42 | + """ |
| 43 | + Given the updated lists of lists from `get_geolocation()`, this function |
| 44 | + creates a new CSV. |
| 45 | + """ |
| 46 | + with open('output.csv', 'wb') as f: |
| 47 | + writer = csv.writer(f) |
| 48 | + writer.writerows(updated_address_list) |
| 49 | + print "All done!" |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + csv_file = '25_sample_csv.csv' |
| 54 | + all_the_ip_address = get_addresses(csv_file) |
| 55 | + updated_address_list = get_geolocation(all_the_ip_address) |
| 56 | + create_csv(updated_address_list) |
0 commit comments