如果你对Python数据编组这种计算机语言有不解之处时,或想了解Python数据编组的实际相关应用方案时,你可以浏览我们的文章,希望我们的文章就是对你会有所收获。以下是文章的具体介绍。
使用前一节中介绍的模块,可以实现在文件中对字符串的读写。然而,有的时候,需要传递其它类型的数据。如list、tuple、dictionary和其它对象。在Python数据编组中,你可以使用Pickling来完成。你可以使用Python标准库中的“pickle”模块完成数据编组。下面,我们来编组一个包含字符串和数字的list:
- view plaincopy to clipboardprint?
- import pickle
- fileHandle = open ( 'pickleFile.txt', 'w' )
- testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]
- pickle.dump ( testList, fileHandle )
- fileHandle.close()
- import pickle
- fileHandle = open ( 'pickleFile.txt', 'w' )
- testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]
- 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()
现在Python数据编组试试存储更加复杂的数据:
- 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()
如上所述,使用Python数据编组的“pickle”模块编组确实很简单。众多对象可以通过它来存储到文件中。如果可以的话,“cPickle”同样胜任这个工作。它和“pickle”模块一样,但是速度更快:
- view plaincopy to clipboardprint?
- import cPickle
- fileHandle = open ( 'pickleFile.txt', 'w' )
- cPickle.dump ( 1776, fileHandle )
- fileHandle.close()
以上是对Python数据编组实际应用的相关内容的部分介绍。