python 读取json为list及向json文件追加数据
生活随笔
收集整理的這篇文章主要介紹了
python 读取json为list及向json文件追加数据
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
""" 讀取json數(shù)據(jù)到list """
def read_json_list(json_file):if not (os.path.exists(json_file) and os.path.isfile(json_file)):with open(json_file, 'w') as f:f.write('[]')with open(json_file, 'r', encoding='utf-8') as f:try:school_list = json.load(f)except:school_list = []return school_list
""" 以追加方式向json文件追加list數(shù)據(jù) """
def add_to_josn(school_brochure):remove_last_char(json_file)with open(json_file, 'a', encoding='utf-8') as f:if os.path.getsize(json_file) > 10:# 粗暴判斷是否已有數(shù)據(jù)記錄f.write(',')f.write(json.dumps(school_brochure, ensure_ascii=False))f.write("]")
""" 刪除文件最后一個字符 """
def remove_last_char(json_file):with open(json_file, 'rb+') as f:f.seek(-1, os.SEEK_END)f.truncate()
總結(jié)
以上是生活随笔為你收集整理的python 读取json为list及向json文件追加数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]Xdebug----Failed
- 下一篇: Cmder集成到VS Code (新旧版