File tree 4 files changed +40
-0
lines changed
Python/CSV-IP-geolocation
4 files changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 )
Original file line number Diff line number Diff line change
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 } " )
You can’t perform that action at this time.
0 commit comments