当前位置:Gxlcms > Python > Python编程中对文件和存储器的读写示例代码

Python编程中对文件和存储器的读写示例代码

时间:2021-07-01 10:21:17 帮助过:26人阅读

这篇文章主要介绍了Python编程中对文件和存储器的读写示例,包括使用cPickle储存器存储对象的例子,需要的朋友可以参考下

1.文件的写入和读取


  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # Filename: using_file.py
  4. # 文件是创建和读取
  5. s = '''''我们都是木头人,
  6. 不许说话不许动!'''
  7. # 创建一个文件,并且写入字符
  8. f = file('test_file.txt', 'w')
  9. f.write(s)
  10. f.close()
  11. # 读取文件,逐行打印
  12. f = file('test_file.txt')
  13. while True:
  14. line = f.readline()
  15. # 如果line长度为0,说明文件已经读完了
  16. if len(line) == 0:
  17. break
  18. # 默认的换行符也读出来了,所以用逗号取代print函数的换行符
  19. print line,
  20. f.close()

执行结果:


  1. 我们都是木头人,
  2. 不许说话不许动!


2.存储器的写入和读取


  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # Filename using_pickle.py
  4. # 使用存储器
  5. #加载存储器模块,as后面是别名
  6. #import pickle as p
  7. #书上说cPickle比pickle快很多
  8. import cPickle as p
  9. listpickle = [1, 2, 2, 3]
  10. picklefile = 'picklefile.data'
  11. f = file(picklefile, 'w')
  12. # 写如数据
  13. p.dump(listpickle, f)
  14. f.close()
  15. del listpickle
  16. f = file(picklefile)
  17. # 读取数据
  18. storedlist = p.load(f)
  19. print storedlist
  20. f.close()


执行结果:


  1. [1, 2, 2, 3]

再来看一个使用cPickle储存器存储对象的例子


  1. #!/usr/bin/python
  2. #Filename:pickling.py
  3. import cPickle as p
  4. shoplistfile = 'shoplist.data'
  5. shoplist = ['apple', 'mango', 'carrot']
  6. f = file(shoplistfile, 'w')
  7. p.dump(shoplist, f)
  8. f.close()
  9. del shoplist
  10. f = file(shoplistfile)
  11. storedlist = p.load(f)
  12. print storedlist

以上就是Python编程中对文件和存储器的读写示例代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行