The pickle module is used in Python for data persistence, and the basic usage involves both dump and load, or dumps and loads.
Pickle in the use of the process has a feature, is due to its special content tag, so that file dump several times, it must load several times to read out the data, in code to show is the following form:
ImportPicklea=1b=2C=3With Open ("Ceshi.txt","WB") as F:pickle.dump (a,f) pickle.dump (b,f) pickle.dump (c,f) F=open ("Ceshi.txt","RB") with open ("Ceshi.txt","RB") as F:Print(Pickle.load (f))
The end result is:
1
If you want to read all the values, it can only be dump a few times, load several times, as follows:
ImportPicklea=1b=2C=3With Open ("Ceshi.txt","WB") as F:pickle.dump (a,f) pickle.dump (b,f) pickle.dump (c,f) F=open ("Ceshi.txt","RB") with open ("Ceshi.txt","RB") as F:Print(Pickle.load (f))Print(Pickle.load (f))Print(Pickle.load (f))
The end result is:
1
2
3
When we read and write files later, it is not possible to remember all the dump times, and we cannot use the load multiple times to extract the value accurately. We can use another way to make the curve salvation:
The direct infinite Loop executes the pickle.load command until its error is stopped.
ImportPicklea=1b=2C=3With Open ("Ceshi.txt","WB") as F:pickle.dump (a,f) pickle.dump (b,f) pickle.dump (c,f) F=open ("Ceshi.txt","RB") with open ("Ceshi.txt","RB") as F: whileTrue:Try: Print(Pickle.load (f))except: Break
The end result is:
1
2
3
In this way, we can also do the pickle generated file content to take out all.
Python file operation: Pickle module read problem after multiple dump