|
| 1 | +importcsv |
| 2 | +importrequests |
| 3 | + |
| 4 | + |
| 5 | +defget_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 | +withopen(filename,'rb')asf: |
| 13 | +reader=csv.reader(f) |
| 14 | +forrowinreader: |
| 15 | +all_addresses.append(row) |
| 16 | +returnall_addresses |
| 17 | + |
| 18 | + |
| 19 | +defget_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 | +forlineinall_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 | +returnupdated_addresses |
| 39 | + |
| 40 | + |
| 41 | +defcreate_csv(updated_address_list): |
| 42 | +""" |
| 43 | + Given the updated lists of lists from `get_geolocation()`, this function |
| 44 | + creates a new CSV. |
| 45 | + """ |
| 46 | +withopen('output.csv','wb')asf: |
| 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) |