簡體   English   中英

python 如何讓我的代碼保存數據以便下次運行時使用

[英]python how to make my code save data to use it for the next time it runs

我正在制作一個代碼,可以覆蓋到 restcountries.com 並通過給定的國家名稱獲取人口數量。 然后,下一次運行時,它會將這個數字與同一個國家的人口數量進行比較,並判斷它是增長、保持不變還是比上次少。 到目前為止,我已經設法告訴了人口數量。 現在我希望它在下次運行時保存人口數量和國家名稱,以便它可以比較它們並檢查您是否第二次使用相同的國家名稱(否則將無效)。 我在 web 上找不到與我的任務相關的答案:\

這是我的代碼:

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(' ', '%20') + '?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)

在這種情況下,您可以使用數據庫 noSql 數據庫來保存記錄並管理您的數據。

但是,如果您想要一個快速的解決方案,只需一個 csv 文件來存儲最后獲取的數據並使用實時數據與它進行比較。

小心。

您可以將 SQLite DB 用於您的用例,任何類型的存儲都可以使用,但是如果需要以有組織的方式管理和訪問數據,我建議您使用 SQLite,因為您不需要任何數據庫服務器為了它。

先決條件

  • 在您的系統上安裝 sqlite3 -鏈接

架構.sql

DROP TABLE IF EXISTS countries;

CREATE TABLE countries(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    population INTEGER NOT NULL
);

創建數據庫.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())

您可以在程序開始時運行createDb() ,還應在調用createDB()之前檢查 countryDB.sqlite 是否存在。

要訪問數據庫,您可以以類似的方式編寫代碼:

import sqlite3
connection = sqlite3.connect('countryDB.sqlite')

cursor = connection.cursor()
cursor.execute("SELECT * from countries") # or any other SQL commands.

有關更多信息,請參閱文檔 -鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM