Python file operation: Pickle module read problem after multiple dump

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.