您的位置:首页 > 编程语言 > Python开发

简明Python教程读书笔记-9 文件操作

2011-02-11 15:31 155 查看
1. 文件读写

Python中通过file类实现对文件的操作,如f = file('test.txt', 'w')表示以写方式打开文件test.txt,如果不指定打开方式,默认为读方式打开文件。文件的打开方式包括读、写和追加

2. 对象的持久化存储

在文件中存储对象,可以通过文件恢复对象的值。通过pickle和cPickle类实现(后者通过C编写,速度较快)

import cPickle 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 = open(shoplistfile, 'wb')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = open(shoplistfile, 'rb')
storedlist = p.load(f)
print(storedlist)


Python3版本中,文件打开方式必须为wb和rb
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: