Python-json&pickle Serialization--026

Source: Internet
Author: User
Tags serialization

Two modules for serialization

    • JSON, used to convert between string and Python data types
    • Pickle for conversion between Python-specific types and Python data types

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

Example one:

1. File Write

info = {        ' name ': ' Robin ',        ' old ': '    }f = open (' E:\python-project\ceshi.txt ', ' W ') f.write (str (info)) F.close ()

2. File read

f = open (' E:\python-project\ceshi.txt ', ' r ') data = eval (F.read ()) F.close () print (data[' old ')

  

Example two: (using JSON serialization)

1. File Write

Import jsoninfo = {        ' name ': ' Robin ',        ' old ': '    }f = open (' E:\python-project\ceshi.txt ', ' W ') F.write ( Json.dumps (info))  #相当于json. Dump (info,f) f.close ()

  

2. File read

Import jsonf = open (' E:\python-project\ceshi.txt ', ' r ') data = Json.loads (F.read ()) #相当于data = Json.load (f) f.close () Print (data[' old ')

Strength III: (using pickle serialization)

1. File Write

Import pickledef SAS (name):    print ("Hello", name) info = {        ' name ': ' Robin ',        ' old ': ' + ',        ' func ': SAS    }f = open (' E:\python-project\ceshi.txt ', ' WB ') F.write (Pickle.dumps (info))    #相当于pickle. Dump (info,f) f.close ()

2. File read

Import pickledef SAS (name):    print ("Hello2", name) F = open (' E:\python-project\ceshi.txt ', ' RB ') data = Pickle.loads ( F.read ())  #相当于data = Pickle.load (f) f.close () print (data[' func '] (' wen '))

  

Python-json&pickle Serialization--026

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.