1. 程式人生 > >python模組之json_pickle_shelve

python模組之json_pickle_shelve

#!/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'])
複製程式碼