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'datax_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)
原文地址:https://www.cnblogs.com/feng-hao/p/10822631.html