Python数据编组对文字串的读写 - Go语言中文社区

Python数据编组对文字串的读写


如果你对Python数据编组这种计算机语言有不解之处时,或想了解Python数据编组的实际相关应用方案时,你可以浏览我们的文章,希望我们的文章就是对你会有所收获。以下是文章的具体介绍。

使用前一节中介绍的模块,可以实现在文件中对字符串的读写。然而,有的时候,需要传递其它类型的数据。如list、tuple、dictionary和其它对象。在Python数据编组中,你可以使用Pickling来完成。你可以使用Python标准库中的“pickle”模块完成数据编组。下面,我们来编组一个包含字符串和数字的list:

  1. view plaincopy to clipboardprint?  
  2. import pickle   
  3.  
  4. fileHandle = open ( 'pickleFile.txt', 'w' )   
  5. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]   
  6. pickle.dump ( testList, fileHandle )   
  7. fileHandle.close()   
  8.  
  9. import pickle  
  10.  
  11. fileHandle = open ( 'pickleFile.txt', 'w' )  
  12. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]  
  13. pickle.dump ( testList, fileHandle )  
  14. fileHandle.close()  

拆分编组同样不难:

  1. view plaincopy to clipboardprint?  
  2. import pickle   
  3.  
  4. fileHandle = open ( 'pickleFile.txt' )   
  5. testList = pickle.load ( fileHandle )   
  6. fileHandle.close()   
  7.  
  8. import pickle  
  9.  
  10. fileHandle = open ( 'pickleFile.txt' )  
  11. testList = pickle.load ( fileHandle )  
  12. fileHandle.close()  
  13.  

现在Python数据编组试试存储更加复杂的数据:

  1. view plaincopy to clipboardprint?  
  2. import pickle   
  3.  
  4. fileHandle = open ( 'pickleFile.txt', 'w' )   
  5. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson',
     [ 1, 2, 7 ] ]   
  6. pickle.dump ( testList, fileHandle )   
  7. fileHandle.close()   
  8.  
  9. import pickle  
  10.  
  11. fileHandle = open ( 'pickleFile.txt', 'w' )  
  12. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', 

    [ 1, 2, 7 ] ]  
  13. pickle.dump ( testList, fileHandle )  
  14. fileHandle.close()view plaincopy to clipboardprint?  
  15. import pickle   
  16.  
  17. fileHandle = open ( 'pickleFile.txt' )   
  18. testList = pickle.load ( fileHandle )   
  19. fileHandle.close()   
  20.  
  21. import pickle  
  22.  
  23. fileHandle = open ( 'pickleFile.txt' )  
  24. testList = pickle.load ( fileHandle )  
  25. fileHandle.close()   
  26.  

如上所述,使用Python数据编组的“pickle”模块编组确实很简单。众多对象可以通过它来存储到文件中。如果可以的话,“cPickle”同样胜任这个工作。它和“pickle”模块一样,但是速度更快:

  1. view plaincopy to clipboardprint?  
  2. import cPickle   
  3.  
  4. fileHandle = open ( 'pickleFile.txt', 'w' )   
  5. cPickle.dump ( 1776, fileHandle )   
  6. fileHandle.close()   

以上是对Python数据编组实际应用的相关内容的部分介绍。

【责任编辑:孙巧华 TEL:(010)68476606】

点赞 0
版权声明:本文来源51CTO,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:http://developer.51cto.com/art/201003/188591.htm
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 15:47:53
  • 阅读 ( 484 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢