Python如何存儲(chǔ)數(shù)據(jù)到j(luò)son文件
1 前言
很多程序都要求用戶輸入某種信息,程序一般將信息存儲(chǔ)在列表和字典等數(shù)據(jù)結(jié)構(gòu)中。
用戶關(guān)閉程序時(shí),就需要將信息進(jìn)行保存,一種簡(jiǎn)單的方式是使用模塊json來(lái)存儲(chǔ)數(shù)據(jù)。
模塊json讓你能夠?qū)⒑?jiǎn)單的Python數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)存到文件中,并在程序再次運(yùn)行時(shí)加載該文件中的數(shù)據(jù)。
還可以使用json在Python程序之間分享數(shù)據(jù),更重要的是,JSON(JavaScript Object Notation,最初由JavaScript開(kāi)發(fā))格式的數(shù)據(jù)文件能被很多編程語(yǔ)言兼容。
2 使用json.dump( )
實(shí)現(xiàn)代碼:
import jsonnumbers = [1, 3, 5, 7, 11]filename = 'numbers.json'with open(filename, ’w’) as file_obj: json.dump(numbers, file_obj)
運(yùn)行結(jié)果:
工作原理:
導(dǎo)入json模塊。 定義存儲(chǔ)數(shù)據(jù)的列表。 指定存儲(chǔ)數(shù)據(jù)的文件名稱。 以寫(xiě)模式打開(kāi)存儲(chǔ)數(shù)據(jù)用的文件。 調(diào)用json.dump( )存儲(chǔ)數(shù)據(jù)。3 使用json.load( )
實(shí)現(xiàn)代碼:
import jsonfilename = 'numbers.json'with open(filename) as file_obj: numbers = json.load(file_obj)print(numbers)
運(yùn)行結(jié)果:
工作原理:
只讀模式打開(kāi)文件。 json.load( )加載文件中信息并存儲(chǔ)到變量numbers中。 打印numbers中數(shù)字信息。以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python sorted排序方法如何實(shí)現(xiàn)2. Python基于requests實(shí)現(xiàn)模擬上傳文件3. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車4. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題5. python利用opencv實(shí)現(xiàn)顏色檢測(cè)6. Python文本文件的合并操作方法代碼實(shí)例7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫(huà)特效9. asp讀取xml文件和記數(shù)10. Python獲取B站粉絲數(shù)的示例代碼
