Python provides a standard module, called Pickle. With it you can store any Python object in a file, and then you
And you can take it out in its intact. This is referred to as a persistent storage object.
There is another module called Cpickle, which is functionally identical to the Pickle module, except that it is written in C, so
Much faster (1000 times times faster than pickle). You can use either of them, and we'll use the Cpickle module here. Remember
The two modules are referred to as pickle modules.
Memory
1 ImportCpickle as P #取一个代名词p to simplify Cpickle2Shoplistfile ='Shoplist.data'3 4Shoplist = ['Apple','Mango','Carrot'] #创建一个列表数据shoplist5 6f = File (Shoplistfile,'W'#以W模式打开shoplistfile mode to open the file Note: If the file exists, first empty, then add the content. 7 p.dump (shoplist,f) #通过dump函数将shoplist内容写入到f中8 f.close () #关闭f文档9 Ten One delshoplist #删除shoplist文件 A -f =file (shoplistfile) #以r模式打开shoplistfile -Storedlist =p.load (f) #通过load函数读取f中的文件内容 storage to Storedlist the PrintStoredlist #打印出来
First of all, please note that we have used import: As syntax. This is a convenient way to make it easier for us to use shorter module names.
In this case, it also allows us to switch to another module (Cpickle or pickle) by simply changing one line! In
The rest of the program, we simply refer to this module as P.
To store an object in a file, first open a file object in write mode, and then call the dump function of the storage module to
As stored in the open file. This process is called storage .
Next, we use the return of the load function of the Pickle module to retrieve the object. This process is called fetching storage .
Python Basic Learning 6---memory