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: