python開發_pickle


pickle模塊使用的數據格式是python專用的,並且不同版本不向后兼容,同時也不能被其他語言說識別。要和其他語言交互,可以使用內置的json包使用pickle模塊你可以把Python對象直接保存到文件,而不需要把他們轉化為字符串,也不用底層的文件訪問操作把它們寫入到一個二進制文件里。 pickle模塊會創建一個python語言專用的二進制格式,你基本上不用考慮任何文件細節,它會幫你干凈利落地完成讀寫獨享操作,唯一需要的只是一個合法的文件句柄。
        pickle模塊中的兩個主要函數是dump()和load()。dump()函數接受一個文件句柄和一個數據對象作為參數,把數據對象以特定的格式保存到給定的文件中。當我們使用load()函數從文件中取出已保存的對象時,pickle知道如何恢復這些對象到它們本來的格式。
        dumps()函數執行和dump() 函數相同的序列化。取代接受流對象並將序列化后的數據保存到磁盤文件,這個函數簡單的返回序列化的數據。
        loads()函數執行和load() 函數一樣的反序列化。取代接受一個流對象並去文件讀取序列化后的數據,它接受包含序列化后的數據的str對象, 直接返回的對象。
        cPickle是pickle得一個更快得C語言編譯版本。
        pickle和cPickle相當於java的序列化和反序列化操作

以上來源:http://www.2cto.com/kf/201009/74973.html

下面是python的API中的Example:

 1 # Simple example presenting how persistent ID can be used to pickle
 2 # external objects by reference.
 3 
 4 import pickle
 5 import sqlite3
 6 from collections import namedtuple
 7 
 8 # Simple class representing a record in our database.
 9 MemoRecord = namedtuple("MemoRecord", "key, task")
10 
11 class DBPickler(pickle.Pickler):
12 
13     def persistent_id(self, obj):
14         # Instead of pickling MemoRecord as a regular class instance, we emit a
15         # persistent ID.
16         if isinstance(obj, MemoRecord):
17             # Here, our persistent ID is simply a tuple, containing a tag and a
18             # key, which refers to a specific record in the database.
19             return ("MemoRecord", obj.key)
20         else:
21             # If obj does not have a persistent ID, return None. This means obj
22             # needs to be pickled as usual.
23             return None
24 
25 
26 class DBUnpickler(pickle.Unpickler):
27 
28     def __init__(self, file, connection):
29         super().__init__(file)
30         self.connection = connection
31 
32     def persistent_load(self, pid):
33         # This method is invoked whenever a persistent ID is encountered.
34         # Here, pid is the tuple returned by DBPickler.
35         cursor = self.connection.cursor()
36         type_tag, key_id = pid
37         if type_tag == "MemoRecord":
38             # Fetch the referenced record from the database and return it.
39             cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
40             key, task = cursor.fetchone()
41             return MemoRecord(key, task)
42         else:
43             # Always raises an error if you cannot return the correct object.
44             # Otherwise, the unpickler will think None is the object referenced
45             # by the persistent ID.
46             raise pickle.UnpicklingError("unsupported persistent object")
47 
48 
49 def main():
50     import io
51     import pprint
52 
53     # Initialize and populate our database.
54     conn = sqlite3.connect(":memory:")
55     cursor = conn.cursor()
56     cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
57     tasks = (
58         'give food to fish',
59         'prepare group meeting',
60         'fight with a zebra',
61         )
62     for task in tasks:
63         cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))
64 
65     # Fetch the records to be pickled.
66     cursor.execute("SELECT * FROM memos")
67     memos = [MemoRecord(key, task) for key, task in cursor]
68     # Save the records using our custom DBPickler.
69     file = io.BytesIO()
70     DBPickler(file).dump(memos)
71 
72     print("Pickled records:")
73     pprint.pprint(memos)
74 
75     # Update a record, just for good measure.
76     cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")
77 
78     # Load the records from the pickle data stream.
79     file.seek(0)
80     memos = DBUnpickler(file, conn).load()
81 
82     print("Unpickled records:")
83     pprint.pprint(memos)
84 
85 
86 if __name__ == '__main__':
87     main()

運行效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM