Python---serial

import pickle
import pickletools
import json

def pickle1():
    list1={}
    list1['name']='jack'
    list1['age']=22
    with open('data.pickle', mode='wb') as file:
        pickle.dump(list1, file)

def pickle2():
    with open('data.pickle', mode='rb') as file:
        list1=pickle.load(file)
        print(list1)

def pickle4():
    with open('data.pickle', mode='rb') as file:
        pickletools.dis(file)

def pickle3():
    list1={}
    list1['name']='hellen'
    list1['age']=18
    b=pickle.dumps(list1)
    list2=pickle.loads(b)
    print(list2)

def json1():
    list1={}
    list1['name']='cindy'
    list1['age']=29
    with open('data.json', mode='w', encoding='utf-8') as f:
        json.dump(list1, f, indent=2)
'''
1. mode,encoding: json is based on character, so mode should not be byte, encoding should be set
2. indent: one value as one line
3. data type in json and python:
    dictionary--------json: object
    list-----------json:array
    string-------json:string
    integer------json:integer
    True---------json:true
    False--------json:false
    None--------json:null
    float--------json:real number
'''

def json2():
    with open('data.json', mode='r', encoding='utf-8') as f:
        list1 = json.load(f)
        print(list1)

if __name__ == '__main__':
    pickle1()
    pickle2()
    pickle3()
    pickle4()
    json1()
    json2()

 


posted @ 2015-12-28 20:10  xfei.zhang  阅读(264)  评论(0编辑  收藏  举报