How to read and write text strings by grouping Python data
How to group Python data to read and write text strings, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Using the module described in the previous section, you can read and write strings in a file. Sometimes, however, other types of data need to be passed. Such as list, tuple, dictionary, and other objects. In Python data marshalling, you can use Pickling to do this. You can use the "pickle" module in the Python standard library to complete data marshalling. Next, let's marshal a list that contains strings and numbers:
View plaincopy to clipboardprint? Import pickle fileHandle = open ('pickleFile.txt', 'w') testList = [' This', 2, 'is', 1,' axiom, 0, 'test.'] pickle.dump (testList, fileHandle) fileHandle.close () import pickle fileHandle = open (' pickleFile.txt', 'w') testList = ['This', 2,' is', 1, 'asides, 0,' test.'] pickle.dump (testList FileHandle) fileHandle.close ()
It is also not difficult to split the group:
View plaincopy to clipboardprint? Import pickle fileHandle = open ('pickleFile.txt') testList = pickle.load (fileHandle) fileHandle.close () import pickle fileHandle = open (' pickleFile.txt') testList = pickle.load (fileHandle) fileHandle.close ()
Now try Python data marshalling to store more complex data:
View plaincopy to clipboardprint?
Import pickle
FileHandle = open ('pickleFile.txt', 'w')
TestList = [123,{ 'Calories': 190},' Mr. Anderson'
[1, 2, 7]]
Pickle.dump (testList, fileHandle)
FileHandle.close ()
Import pickle
FileHandle = open ('pickleFile.txt', 'w')
TestList = [123,{ 'Calories': 190},' Mr. Anderson'
[1, 2, 7]]
Pickle.dump (testList, fileHandle)
FileHandle.close () view plaincopy to clipboardprint?
Import pickle
FileHandle = open ('pickleFile.txt')
TestList = pickle.load (fileHandle)
FileHandle.close ()
Import pickle
FileHandle = open ('pickleFile.txt')
TestList = pickle.load (fileHandle)
FileHandle.close ()
As mentioned above, marshalling the "pickle" module using Python data marshalling is really simple. Many objects can be stored in files through it. If possible, "cPickle" is also qualified for the job. It is the same as the "pickle" module, but faster:
View plaincopy to clipboardprint? Import cPickle fileHandle = open ('pickleFile.txt', 'w') cPickle.dump (1776, fileHandle) fileHandle.close () is it helpful for you to finish reading the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.