python中用json存儲列表字典等文件操作


 

JSON字符串用json.dumps, json.loads JSON文件名用json.dump, json.load

由於需要在腳本重啟后依舊能夠記住之前所使用的列表內容, 故采用json存儲列表文件, 經過測試, 如下代碼可行.

 1 import json  2 
 3 
 4 def write_json(jlist):  5     # 將bx列表寫入json文件
 6     with open('data/bx_list.json', 'w') as f_obj:  
 7  json.dump(jlist, f_obj)  8 
 9 
10 def read_json(): 11     # 讀取存儲於json文件中的列表
12     with open('data/bx_list.json', 'r') as f_obj: 13         jlist = json.load(f_obj) 14     return jlist 15 
16 
17 if __name__ == "__main__": 18     list0=['bx-1', 'bx-2', 'bx-3', 'bx-4'] 19  write_json(list0) 20     list1 = read_json() 21     print(list1) 22     list1.append('bx-5') 23     print(list1) 24  write_json(list1) 25     print(read_json())

運行結果如下:

 

['bx-1', 'bx-2', 'bx-3', 'bx-4'] ['bx-1', 'bx-2', 'bx-3', 'bx-4', 'bx-5'] ['bx-1', 'bx-2', 'bx-3', 'bx-4', 'bx-5']

 

 

備注:

1, 在window系統下, 當前目錄下級目錄表達方式為 'data/bx_list.json' 或者 r'data\bx_list.json', 此外建立json文件並不會建立文件夾, 在這里的data文件夾需要提前建好.

2, with open('data/bx_list.json', 'w') as f_obj: 這一行代碼中,'w'的寫入方式會覆蓋掉原始文件.

 

補充:

python爬蟲requests json與字典對象互相轉換

https://www.cnblogs.com/Lin-Yi/p/7640147.html

 

import requests import json ''' json.loads(json_str) json字符串轉換成字典 json.dumps(dict) 字典轉換成json字符串 '''
# 這是一個ajax發起的get請求,獲取一個json對象
r = requests.get("https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items?os=ios&for_mobile=1&start=0&count=18&loc_id=108288&_=0") json_response = r.content.decode()  # 獲取r的文本 就是一個json字符串

# 將json字符串轉換成dic字典對象
dict_json = json.loads(json_response) print(type(dict_json)) # 將字典轉換成json字符串
str_json = json.dumps( dict_json ) print(type(str_json)) # 字典轉換成json 存入本地文件
with open('./a.txt','w') as f: # 設置不轉換成ascii json字符串首縮進
    f.write( json.dumps( dict_json,ensure_ascii=False,indent=2 ) )

 

注意:

python將字典轉為json數據中文亂碼,可用如下代碼解決

json.dumps(jsonData,ensure_ascii=False)

 


免責聲明!

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



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