Home >Backend Development >Python Tutorial >A brief introduction to the json module and pickle module in Python (with examples)
This article brings you a brief introduction to the json module and pickle module in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The json module and pickle in Python are both used for serialization and deserialization of data. They provide the same methods: dumps, dump, loads, load
dumps(obj): Serialize the object to str.
dump(obj, fp): Serialize the object to str and store it in the file.
Deserialize the (serialized) string into a Python object.
in the file into a Python object. Although the json and pickle modules are both used for serialization and deserialization of data, there are still many
differences:
Universality:Processed data types:
Processed data type:
Used space:
The following is a simple example of pickle file operation:
>>> import pickle >>> dic = {'a': 111, 'b': 222, 'c': 333} >>> f = open('D:/pk_file.pk', 'wb') >>> lst = [1, 2, 4, 5] >>> # 将字典对象和列表对象序列化,并存入文件,文件名后缀自定义为.pk >>> pickle.dump(dic, f) >>> pickle.dump(lst, f) >>> f.close() >>> # 将文件中的Python对象按写入顺序读取出来,且一次读取一个对象 >>> pk_f = open('D:/pk_file.pk', 'rb') >>> result = pickle.load(pk_f) >>> type(result) <class 'dict'> >>> result {'a': 111, 'b': 222, 'c': 333} >>> other_result = pickle.load(pk_f) >>> type(other_result) <class 'list'> >>> other_result [1, 2, 4, 5] >>>
The above is the entire content of this article, For more exciting content about python, you can pay attention to the
Python video tutorialand
python article tutorialcolumns on the PHP Chinese website! ! !
The above is the detailed content of A brief introduction to the json module and pickle module in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!