Python USES the pickle module to store data error resolution sample code

  • 2020-07-21 09:10:21
  • OfStack

In this paper, Python USES pickle module to store data error reporting solutions, which are shown in the form of code, as follows.

Let's start with the pickle module

pickle provides a simple persistence function. Objects can be stored on disk as files. The pickle module can only be used in python. Almost all data types (lists, dictionaries, collections, classes, etc.) in python can be serialized using pickle. pickle serialized data, poor readability, people 1 can not recognize.

Next, let's look at Python's solution for storing data errors using the pickle module.

Code:


#  Write error 
TypeError: write() argument must be str, not bytes


#  Read error 
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 0: illegal multibyte sequence

Solutions:


def storeTree(inputTree, fielname):
  import pickle
  #  When writing documents, indicate  'wb'
  fw = open(fielname, 'wb')
  pickle.dump(inputTree, fw)
  fw.close()

def grabTree(filename):
  import pickle
   #  When reading a document, indicate  'rb'
  fr = open(filename, 'rb')
  fr = open(filename)
  return pickle.load(fr)

storeTree(myTree, 'classifierStorage.txt')
print(grabTree('classifierStorage.txt'))

Output:


{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

Process finished with exit code 0

conclusion

That is the end of this article on Python using the pickle module to store data error resolution sample code, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: