Python: serialization and data persistence, python serialization

Source: Internet
Author: User

Python: serialization and data persistence, python serialization

Data Persistence methods include:

1. Normal file writing without format: write data directly to the file

2. Normal serialized write: json, pickle

3. DBM mode: shelve, dbm

 

Related content:
  • Json
  • Pickle
  • Shelve
  • Dbm

 

Start Time:

 

Json: Introduction:

Write the data in plaintext to the file according to the specified format (for example, the format is dictionary, and the file is dictionary). The data type is bytes. For example, "Chinese" is converted to Unicode encoding.

Usage:
  • First, import the module import json
  • Serialization:
    • Json. dump (serialized object, file object)
    • Json. dumps (serialized object), the return value is a string, you need to manually write this string into the file
      Print ("------ json serialization --------") import jsonimport timeinfo = {'date': time. localtime (), 'name': 'Chinese'} f = open ("test.txt", "w") print ("--------- dump ---------") # json. dump (info, f) # f. close () print ("--------- dumps, ---------") f. write (json. dumps (info) f. close ()
  • Deserialization:
    • Json. load (file object)
    • Json. loads (string)
      Print ("------ deserialization --------") import jsonf = open ("test.txt", "r") print ("------- load ----------") # data = json. load (f) #1 # print (data) print ("------- loads ----------") d2 = json. loads (f. read () print (d2) f. close ()

 

 

For multiple dump \ dumps, how to load \ loads:
  • You need to manually divide the data during dump.
Print ("------ json serialization --------") import jsonimport timeinfo = {'date': time. localtime (), 'name': 'Chinese' # 'func': hello # Note: json deserialization functions} info2 = ['1', 2, 3, 4] f = open ("test.txt", "w") print ("--------- dumps, ---------") # Use '\ n' to distinguish two data copies. write (json. dumps (info) + "\ n") f. write (json. dumps (info2) + "\ n") f. close ()
import jsonwith open("test.txt") as f:    a=json.loads(f.readline())    b=json.loads(f.readline())    print(a,b)

 

Pickle: Introduction:
  • Conversion between Python data types and Python-specific binary formats
  • The protocol parameter specifies the protocol version for serialization. By default, pikkle is used to serialize data by bytes. The file opening method must be in binary format.
Usage:
  • First import the module import pickle
  • Serialization:
    • Pickle. dump (serialized object, file object)
    • Pickle. dumps (serialized object), the return value is a string, you need to manually write this string into the file
      Import pickleinfo = {'name': '1', 'age': 2,} f = open ("test2.txt", "wb") pickle. dump (info, f) # serialization method 1 # f. write (pickle. dumps (info) # serialization method 2f. close ()
  • Deserialization:
    • Pickle. load (file object)
    • Pickle. loads (string)
      Print ("------ deserialization --------") import picklef = open ("test2.txt", "rb") data = pickle. loads (f. read () # deserialization method 1 print (data) # data = pickle. load (f) # method 2 # print (data) f. close ()

 

Shelve: Introduction:
  • It is used to persist Python data to a disk and perform operations similar to dict.
Usage:

  • First import the module import
  • Shelve open a file: shelve file object = shelve. open (file name)
  • Write: shelve file object [key] = value
  • Read: shelve file object. get (key)
Import shelve, timed = shelve. open ('shelve _ test') # open a file print ("---------- write ----------") info = {"name": 'lilei', "sex ": "man"} name = ["autuman", "zhangsan ", "lisi"] d ["teacher"] = named ["student"] = infod ["date"] = time. ctime () print ("-------- read ------------") print (d. get ("teacher") print (d. get ("student") print (d. get ("date") d. close ()

 

Shelve can easily serialize Custom Data Types and functions:

Import shelve, timeclass A: def hello (self): print ("123") d = shelve. open ('shelve _ test') # open a file print ("---------- write ----------") d ['class'] = Aprint ("-------- read ------------") a = d. get ('class') (). hello () d. close ()

Dbm: Introduction:
  • Dbm is very similar to shelve, but the key and value of dbm must be of the string type.
  • Dbm data written by default is bytes, and all strings are serialized into bytes
Usage:
  • First, import the module imort dbm [note that there are many different dbm which can be selected for use. The default value is used here]
  • Open File: dbm object = dbm. open (file name, open mode)
  • Write: dbm object [key] = value
  • Read: dbm object [key]
Import dbmdb = dbm. open ("test.txt", "c") print ("write ". center (50, '-') db ["name"] = "1111111111112" db ["name2"] = "2222222222222" print ("read ". center (50, '-') print (db ["name"]) print (db ["name2"]) db. close ()

 

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.