python模块之json_pickle_shelve

序列化:明显是json重要,并且应用场景多。

#!/usr/bin/env python
# coding:utf-8

import json
## 非常重要的模块,用于不同种编程语言间交换数据。

dic= {"name":'alex',"age":38,"desc":"金角大王"}
print(dic["name"])

data = json.dumps(dic) # 所有的单引号都会变成双引号,汉字会变
print(data)
print(type(data))


data2 = json.loads(data) # 还原为字典,需要原数据符合json规范
print(data2["desc"])

# 文件 处理
# with open('data.json', 'w') as f:
#     json.dump(data2, f) # 写入文件,不需要write方法

#
# print("----------------------------------")
# # 读出文件
# with open('data.json', 'r') as f:
#     data3 = json.load(f)
#     print(data3)



## pickle和json的用法几乎一样, 功能是序列化。
## 参考:http://www.cnblogs.com/yuanchenqi/articles/5732581.html
import pickle

pk = pickle.dumps(dic) # 字节序列化
print(pk)

with open("pk.txt","wb") as f:
    f.write(pk)


with open("pk.txt","rb") as f:
    fpk = pickle.load(f)
    print(fpk)

 

shelve模块:

#!/usr/bin/env python
# coding:utf-8

import shelve

# shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
## 将一个字典存入文本
f = shelve.open(r"shelve2")
f['grp1'] = {'name':"jerry",'age':'22'}
f['grp2'] = {'name':"jerry",'age':'22'}
f['dept'] = {'dept.':"Admin",'group':'books'}

f.close()

# 取文件中的字典文本
f = shelve.open(r"shelve2")
print(f.get('dept'))
print(f.get('dept')["group"])

 

获取json格式天气数据,

#!/usr/bin/env python
# coding:utf-8

import requests,json

rsp = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=昆山")
rsp.encoding = 'utf-8'
# print(rsp.text)

dic = json.loads(rsp.text) # 拿到对象的内容
print(dic)
print(dic['data']['city'])
print(dic['data']['forecast'][1]['date'])
print(dic['data']['forecast'][1]['high'])
print(dic['data']['forecast'][1]['fengli'])

 

posted @ 2018-05-16 20:46  枫若雪  阅读(128)  评论(0编辑  收藏  举报