圆月山庄资源网 Design By www.vgjia.com

1.文件的写入和读取

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

 

执行结果:

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

 
2.存储器的写入和读取

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


执行结果:

[1, 2, 2, 3]

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

#!/usr/bin/python 
#Filename:pickling.py 
 
import cPickle as p 
 
shoplistfile = 'shoplist.data' 
 
shoplist = ['apple', 'mango', 'carrot'] 
 
f = file(shoplistfile, 'w') 
p.dump(shoplist, f) 
f.close() 
 
del shoplist 
 
f = file(shoplistfile) 
storedlist = p.load(f) 
print storedlist 

标签:
Python,文件,存储器

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com