首页 > 代码库 > python持久化
python持久化
将对象转为二进制字节流(pickle)
import pickle my_list = [1,2,3] pickle_file = open(‘my_list.pkl‘, ‘wb‘) #注意二进制写入 pickle.dump(my_list, pickle_file) pickle_file.close()
二进制转为对象
import pickle pickle_file = open(‘my_list.pkl‘, ‘rb‘) my_list = pickle.load(pickle_file)
实例
1泡菜化(持久化)城市字典
import pickle city = {‘beijing‘:121212} city_file = fopen(‘city_data.pkl‘, ‘wb‘) pickle.dump(city,city_file) city_file.close()
2获取城市字典
import urllib.request import json import pickle pickle_file = open(‘city_data.pkl‘, ‘rb‘) city = pickle.load(pickle_file) pickle_file.close() password = input(‘请输入城市‘) name1 = city[password] File1 = urllib.request.urlopen(‘http://m.weather.com.cn/data/‘+name1‘) weatherHTML = File1.read().decode(‘utf-8‘) weatherJSON = json.JSONDecoder().decode(weatherHTML) weatherInfo = weatherJOSN[‘weatherinfo‘]
python持久化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。