最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python 存儲json數(shù)據(jù)的操作

 更新時間:2021年05月10日 08:54:58   作者:秋殤閣  
這篇文章主要介紹了python 存儲json數(shù)據(jù)的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

本篇我們將學(xué)習(xí)簡單的json數(shù)據(jù)的存儲

首先我們需要引入json模塊:

import json

這里我們模擬一個常見常見,我們讓用戶輸入用戶名、密碼,在密碼輸入完成后提示用戶再次輸入密碼來確認(rèn)自己的輸入,如果兩次密碼一致,那么我們將用戶名和密碼以json格式寫入文件,否則提示用戶再次輸入密碼。

name = input("please enter your name:")
password = input("please enter your password:")
confirm_password = input("confirm your password:")
while password != confirm_password:
    print("input password inconsistencies,please try again")
    password = input("please enter your password:")
    confirm_password = input("confirm your password:")

我們運行下代碼確保我們的準(zhǔn)備工作沒有問題:

這里寫圖片描述

ok,我們可以通過用戶輸入拿到用戶名和密碼,接下來,我們就需要將兩者以json格式存入文件了。

首先,我們將我們的輸入轉(zhuǎn)化為json對象:

user_info = json.dumps({'username': name, 'password': password}, sort_keys=True, indent=4, ensure_ascii=False)
print(user_info)

這里我們使用了json.dumps函數(shù),該函數(shù) 用于將 Python 對象編碼成 JSON 字符串。

語法:

def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,         allow_nan=True, cls=None, indent=None, separators=None,         default=None, sort_keys=False, **kw) Inferred type: (obj: Any, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: bool, kw: Dict[str, Any]) -> str

其中sort_keys是用來指定在json格式的對象里面是否按照key的名稱來進(jìn)行排序,indent參數(shù)則指定縮進(jìn)的空格數(shù)目。

最后的輸入格式如下:

{
    "password": "us",
    "username": "us"
}

那么接下來我們就將這個json對象寫入到文件中去:

 with open('user_info.json', 'w', encoding='utf-8') as json_file:
    json.dump(user_info, json_file, ensure_ascii=False)
    print("write json file success!")

這里我們需要學(xué)習(xí)一個函數(shù)json.dump:

def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,         allow_nan=True, cls=None, indent=None, separators=None,         default=None, sort_keys=False, **kw) Inferred type: (obj: Any, fp: {write}, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: bool, kw: Dict[str, Any]) -> None 

這個函數(shù)有兩個參數(shù)是我們必須要填寫的:obj(我們要存儲的數(shù)據(jù)), fp(文件句柄,也就是我們要存在那個文件里面)。

ensure_ascii=False這個參數(shù)是處理我們希望在json對象里面可以包含中文的場景

If ensure_ascii is false, then the strings written to fp can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

如果不指定ensure_ascii=False,那么當(dāng)我們的數(shù)據(jù)里面包含中文的時候:

{"username": "zhang\u4e09", "password": "ddd"}

會有如上的顯示內(nèi)容。

我們運行程序,依次輸入用戶名和密碼:

please enter your name:us
please enter your password:us
confirm your password:us
{"username": "us", "password": "us"}
write json file success!
Process finished with exit code 0

然后我們看下文本文件中的內(nèi)容:

這里寫圖片描述

接下來我們就需要學(xué)習(xí)一下怎么讀取json格式的內(nèi)容了。

with open('user_info.json', 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)
    print(data)

讀取json數(shù)據(jù)需要使用json.load函數(shù):

def load(fp, *, cls=None, object_hook=None, parse_float=None,         parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Inferred type: (fp: {read}, Any, cls: Any, object_hook: Any, parse_float: Any, parse_int: Any, parse_constant: Any, object_pairs_hook: Any, kw: Dict[str, Any]) -> Any

這里我們需要提供一個參數(shù)fp,也就是我們要操作的文件句柄。

程序運行輸出:

{"username": "us", "password": "us"}

我們可以打印一下json.load返回的是什么類型的:

 print(type(data))

輸出:

<class 'str'>

可見,這是一個字符串,這是為什么呢?難道不應(yīng)該返回的是python對應(yīng)的對象嗎?

在上面的代碼中我們在寫入文件前面調(diào)用過:

user_info = json.dumps({'username': name, 'password': password}, ensure_ascii=False)

這一行代碼,大家還記得吧,它返回的是一個json字符串,所以上面的例子中我們需要使用json.loads重新反序列化為python對象,這一點大家留意一下,上面的例子我們是為了給大家演示json.loads的相關(guān)用法,使用如下:

data = json.loads(data)
print(type(data))
print(data['username'])

如果沒有這行代碼,那么 data = json.load(json_file)返回的就是我們自己組織的數(shù)據(jù)結(jié)構(gòu)了,如果還是{‘username': name, ‘password': password}這種格式,那么返回就是一個字典對象。

下面我們在通過一個list來看一下:

data = [1,2,3,4,5]
with open('user_info.json', 'w', encoding='utf-8') as json_file:
    json.dump(data, json_file, ensure_ascii=False)
with open('user_info.json', 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)
    print(type(data))
    print(data)

運行程序:

<class 'list'>

[1, 2, 3, 4, 5]

補(bǔ)充:Python創(chuàng)建并保存json文件,支持?jǐn)?shù)據(jù)更新保存

大家還是直接看代碼吧~

import json
class Params():
    """Class that loads hyperparameters from a json file.
        Example:
        ```
        params = Params(json_path)
        print(params.learning_rate)
        params.learning_rate = 0.5  # change the value of learning_rate in params
        ```
        """
    def __init__(self, json_path):
        with open(json_path) as f:
            params = json.load(f)  # 將json格式數(shù)據(jù)轉(zhuǎn)換為字典
            self.__dict__.update(params)
    def save(self, json_path):
        with open(json_path, 'w') as f:
            json.dump(self.__dict__, f, indent=4)  # indent縮進(jìn)級別進(jìn)行漂亮打印
    def update(self, json_path):
        """Loads parameters from json file"""
        with open(json_path) as f:
            params = json.load(f)
            self.__dict__.update(params)
    @property  # Python內(nèi)置的@property裝飾器就是負(fù)責(zé)把一個方法變成屬性調(diào)用的
    def dict(self):
        """Gives dict-like access to Params instance by `params.dict['learning_rate']"""
        return self.__dict__
if __name__ == '__main__':
    parameters = {"SEED": 1,
                  "dataset": "Omniglot",
                  "meta_lr": 1e-3,
                  "num_episodes": 5000,
                  "num_classes": 5,
                  "num_samples": 1,
                  "num_query": 10,
                  "num_steps": 100,
                  "num_inner_tasks": 8,
                  "num_train_updates": 1,
                  "num_eval_updates": 1,
                  "save_summary_steps": 100,
                  "num_workers": 1
                  }
    json_str = json.dumps(parameters, indent=4)
    with open('params.json', 'w') as f:  # 創(chuàng)建一個params.json文件
        f.write(json_str)  # 將json_str寫到文件中
    params = Params('params.json')
    params.SEED = 2   # 修改json中的數(shù)據(jù)
    params.save('params.json')  # 將修改后的數(shù)據(jù)保存

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • python讀取圖片并修改格式與大小的方法

    python讀取圖片并修改格式與大小的方法

    這篇文章主要為大家詳細(xì)介紹了python讀取圖片并修改格式與大小的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python?VisPy庫高性能科學(xué)可視化圖形處理用法實例探究

    Python?VisPy庫高性能科學(xué)可視化圖形處理用法實例探究

    VisPy是一個用于高性能科學(xué)可視化的Python庫,它建立在現(xiàn)代圖形處理單元(GPU)上,旨在提供流暢、交互式的數(shù)據(jù)可視化體驗,本文將深入探討VisPy的基本概念、核心特性以及實際應(yīng)用場景,并通過豐富的示例代碼演示其強(qiáng)大的可視化能力
    2023-12-12
  • Python如何輸出警告信息

    Python如何輸出警告信息

    這篇文章主要介紹了Python如何輸出警告信息,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 在cmd中查看python的安裝路徑方法

    在cmd中查看python的安裝路徑方法

    在本篇文章里小編給大家整理的是關(guān)于怎樣在cmd中查看python的安裝路徑的相關(guān)內(nèi)容,有興趣的朋友們學(xué)習(xí)參考下。
    2019-07-07
  • Python深度學(xué)習(xí)pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet

    Python深度學(xué)習(xí)pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet

    這篇文章主要為大家講解了Python深度學(xué)習(xí)中的pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet的示例解析,有需要的朋友可以借鑒參考下希望能夠有所幫助
    2021-10-10
  • python中extend功能用法舉例

    python中extend功能用法舉例

    這篇文章主要給大家介紹了關(guān)于python中extend功能的相關(guān)資料,Python中的extend()方法是一種非常有用的列表操作,它可以將一個列表中的元素添加到另一個列表的末尾,需要的朋友可以參考下
    2023-08-08
  • python3的數(shù)據(jù)類型及數(shù)據(jù)類型轉(zhuǎn)換實例詳解

    python3的數(shù)據(jù)類型及數(shù)據(jù)類型轉(zhuǎn)換實例詳解

    在本文里小編給大家分享的是關(guān)于python3的數(shù)據(jù)類型及數(shù)據(jù)類型轉(zhuǎn)換以及相關(guān)實例內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2019-08-08
  • python爬取豆瓣評論制作詞云代碼

    python爬取豆瓣評論制作詞云代碼

    大家好,本篇文章主要講的是python爬取豆瓣評論制作詞云代碼,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • Python的Tornado?Web框架深入解析

    Python的Tornado?Web框架深入解析

    這篇文章主要為大家介紹了Python的Tornado Web框架的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • JupyterLab遠(yuǎn)程密碼訪問實現(xiàn)

    JupyterLab遠(yuǎn)程密碼訪問實現(xiàn)

    本文主要介紹了JupyterLab遠(yuǎn)程密碼訪問實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02

最新評論

蒙城县| 全南县| 绵阳市| 呼伦贝尔市| 云南省| 遵义县| 宁南县| 西峡县| 贞丰县| 上饶县| 古田县| 屯昌县| 元朗区| 凤冈县| 凤庆县| 石首市| 正镶白旗| 新宾| 饶河县| 石泉县| 宁化县| 晋宁县| 连平县| 太原市| 获嘉县| 绥化市| 新疆| 广宗县| 汶上县| 嘉黎县| 如东县| 田阳县| 黄骅市| 云林县| 凌海市| 广德县| 东阿县| 丁青县| 敦化市| 抚远县| 和政县|