本章简单了解一下Python对文本文件的读写操作,我们来看例子:
一、文件的读写操作
# -*- coding: gb18030 -*-
#1、写文件
write_str = '''\
Hello, china
123
abcdefg
'''
f = file("a.txt","w")
f.write(write_str)
f.close()
#2、读文件
f=file("a.txt","r")
while True:
line = f.readline()
if len(line) == 0:
break
print line
else:
print "read end!", #使用逗号,为消除自动换行
f.close()
二、其他方法
#3、其他存储器
'''
利用标准模块:pickle;cPickle的pickle.dump() ;pickle.load()方法
'''
import cPickle as p #给模块取别名
shoplist = ['apple','mango','carrot']
#Write to the file
f = file('b.txt', 'w')
p.dump(shoplist, f) #dump the object to a file
f.close()
#Read from file
f = file('b.txt','r')
storedlist = p.load(f)
print storedlist