Skip to content

Commit 2a6b0e7

Browse files
Merge pull request #136 from Nibba2018/csv_ip_geo
Return Geolocation of IP addresses in a CSV file.
2 parents 50f2757 + 13df8e6 commit 2a6b0e7

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

Python/CSV-IP-geolocation/IP_data.csv

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Service,IP
2+
Google,216.58.203.14
3+
Yahoo,98.137.11.164
4+
Facebook,31.13.79.35
5+
LinkedIn,108.174.10.10

Python/CSV-IP-geolocation/README.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Generate geolocation of IP addresses given in a CSV file.
2+
* Extracts the IP addresses from a csv file named `IP_data.csv` where the column name is `IP`.
3+
* Performs a GET request to an [API](https://ip-api.com/).
4+
* Prints the results as `IP => city, state, country` for each IP address extracted.
5+
6+
## Executing script
7+
* `python app.py`
8+
9+
## Output
10+
![output](csv-ip-op.png)

Python/CSV-IP-geolocation/app.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import csv
2+
import requests
3+
4+
# Create a context manager to open `.csv` file.
5+
with open("IP_data.csv") as csvfile:
6+
# Create an iterator which iterates through the rows of the file
7+
# and returns the rows as dictionaries when invoked.
8+
reader = csv.DictReader(csvfile)
9+
10+
# Iterate through the rows.
11+
for row in reader:
12+
# Get the IP address from the `IP` column.
13+
ip_address = row['IP']
14+
15+
# Generate the IP URL and perform a GET request.
16+
api_url = "http://ip-api.com/json/" + ip_address
17+
response = requests.get(api_url).json()
18+
19+
# extract important info to make code readable.
20+
city = response['city']
21+
state = response['regionName']
22+
country = response['country']
23+
24+
# Print results to console output.
25+
print(f"{ip_address} => {city}, {state}, {country}")
19.1 KB
Loading

0 commit comments

Comments
 (0)