python存儲json文件


json讀寫

# 數據存儲:json.dump()和json.load()
# date:2017-07-17
import json
 
file_name = 'D:/json_file.txt'
nums = [3, 4, 5, 7, 1, 9]
# nums = {"name": "Mike", "age": 12}
with open(file_name, 'w') as file_obj:
    '''寫入json文件'''
    json.dump(nums, file_obj)
    print("寫入json文件:", nums)
 
with open(file_name) as file_obj:
    '''讀取json文件'''
    numbers = json.load(file_obj)  # 返回列表數據,也支持字典
    print("讀取json文件:", numbers)
  

運行結果:

寫入json文件: [3, 4, 5, 7, 1, 9]
讀取json文件: [3, 4, 5, 7, 1, 9]

但是在讀寫中文時,存儲的文本則可能會顯示為亂碼,這時,只要將代碼進行如下改動即可

 json.dump(nums, file_obj,ensure_ascii=False)

 但是,保存的json文件可能會擠在一塊,這樣在看起來就會很亂了,所以呢,要使用indent

json.dump(nums, file_obj,indent=4,ensure_ascii=False)

這樣再看保存好的json文件,就會覺得比之前要更清晰了

參考地址 

https://www.cnblogs.com/gongxr/p/7225476.html

https://www.cnblogs.com/veitch-623/p/7685880.html

https://blog.csdn.net/qq_30242609/article/details/57420777


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM