首页 > 代码库 > 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持久化