I'm making a code that reaches out to restcountries.com and gets the population number by given country name. Then, the next time it runs, it compares the number with the same country's population number and tells wether it grew, stayed the same or is less than last time. I've managed so far to tell the population number. Now I want it to save the population number and country name for the next time it runs so it can compare them and check if you used the same country name for the second time (else that would be invalid). I couldn't find an answer on the web that is relevant to my mission :\
This is my code:
import urllib.request
import urllib.parse
import json
# Getting updated list and saving it as "json_data"
country_name = input("Choose country or reset: ").capitalize()
req = 'https://restcountries.com/v3/name/' country_name.replace(' ', ' ') '?fields=name,population'
response = json.loads(urllib.request.urlopen(req).read().decode())
# these two lines are my trial to make a reset option to delete the saved data
if country_name == "Reset":
reset = 1
# Country search function
def search(name):
for p in response:
if p['name']['common'] == name:
return p['population']
country_population = search(country_name)
print(country_population)
CodePudding user response:
You can use Databases in this case noSql data base to save the records and manage your data.
But if you want a fast solution just a csv file to store the last fetched data and use the real time data to compare it to it.
Take Care.
CodePudding user response:
You can use an SQLite DB for your use case, any type of storage would have worked, but if managing and accessing data needs to be done in an organized fashion, I'd suggest going with SQLite as you won't need any DB server for it.
Prerequisite:
- Have sqlite3 installed on your system - Link
schema.sql
DROP TABLE IF EXISTS countries;
CREATE TABLE countries(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
population INTEGER NOT NULL
);
createDB.py
import sqlite3
def createDb():
print(' Creating test.sqlite')
with open('schema.sql', 'r') as f:
connection = sqlite3.connect('countryDB.sqlite')
cursor = connection.cursor()
cursor.executescript(f.read())
You can run createDb() at the start of your program, also you should check if countryDB.sqlite exists or not before calling createDB().
For accessing the DB, you can write your code in similar fasion:
import sqlite3
connection = sqlite3.connect('countryDB.sqlite')
cursor = connection.cursor()
cursor.execute("SELECT * from countries") # or any other SQL commands.
Refer to the docs for more information - Link
