python 教程 第十章、 输入/输出

第十章、 输入/输出
1)    文件

poem = '''Programming is fun use Python!'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

可以使用help(file)来了解详情。

2)    储存器
pickle在文件中储存Python对象,cPickle(C语言,更快)

import cPickle as p
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot', 'donggua']
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close() 

#使用pickle

import pickle
object = someClass()
file   = open(filename, 'wb')     # Create external file
pickle.dump(object, file)         # Save object in file
import pickle
file   = open(filename, 'rb')
object = pickle.load(file)        # Fetch it back later 

#使用shelve

import shelve
object = someClass()
dbase  = shelve.open('filename')
dbase['key'] = object             # Save under key
import shelve
dbase  = shelve.open('filename')
object = dbase['key']             # Fetch it back later
上一篇:python 教程 第十九章、 图形界面编程


下一篇:python 教程 第十二章、 标准库