Python,how do you work (二)
关于python,我上一篇说了一些好的例子和在python中怎么创建class的方法和class的内部方法,构造方法,析构方法等等接下来我将说明怎么python对IO的操作
其实python的文件操作有点像c语言,说实话。感觉比c方便的多。
举例说明一切。
使用file类的read,readline或者wirte方法来执行读写操作
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
感觉很简单吧。
python还有储存器
cPickle就是储存器
下里是例子:
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.d(f)
print storedlist
页:
[1]