[Python practice 08] using general IO of pickle to process files

Source: Internet
Author: User

We have learned how to read and store files, but what we do is to process a specific format. We cannot process all IO operations through the code written above, for this problem, python provides us with an original IO processing tool, namely the pickle engine, which can save and load almost any Python data objects, including the list we want to process now.

For example, for pickle:

The above section describes how to store data to the corresponding file. We can save the processed data to the disk, to the database, or to the network. When another person receives the data you pass, the pickle engine must re-read the data to the python memory as follows:

Next we will use pickle to operate on the previous text. During the operation, we need to import the pickle module, save the data using dump (), and use load () read the data, but pickle requires that we must specify the operation to operate a file during file operations. The detailed code is as follows:

import pickleman= []other = []try:    data = open('sketch.txt')    for each_line in data:        try:            (role,line_spoken) = each_line.split(":",1)            line_spoken = line_spoken.strip()            if role == 'Man':                man.append(line_spoken)            elif role == 'Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()except IOError:    print('The datafile is missing!')try:    with open('man_data.txt','wb') as man_file,open('other_data.txt','wb') as other_file:        pickle.dump(man,man_file)        pickle.dump(other,other_file)except IOError as err:    print('File error:'+str(err))except pickle.PickleError as perr:    print('pickling error:'+str(perr))
In this case, we can save the data to the man_data.txtand other_data.txt files. The file content is as follows:

 

Man_data.txt:

 

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.