python 输入输出
先看一个例子
#coding:utf-8 #Filename:using_flie.py ''' Created on 2012-2-27 @author: goodspeedcheng ''' poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = open('poem.txt','w',encoding='utf-8') f.write(poem) f.close() r = open('poem.txt') while True: line = r.read() #line = r.readline() #line = r.readlines() if len(line) == 0: break print(line) r.close()
>>>line = r.read()
输出结果为
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!>>>line = r.readline()
输出结果为
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
>>>line = r.readlins()
输出结果为
['Programming is fun\n', 'When the work is done\n', 'if you wanna make your work also fun:\n', ' use Python!\n']
储存器
Python提供一个标准的模块,称为pickle
。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
什么东西能用pickle
模块存储?
- 所有Python支持的 原生类型 : 布尔, 整数, 浮点数, 复数, 字符串,
bytes
(字节串)对象, 字节数组, 以及None
. - 由任何原生类型组成的列表,元组,字典和集合。
- 由任何原生类型组成的列表,元组,字典和集合组成的列表,元组,字典和集合(可以一直嵌套下去,直至Python支持的最大递归层数).
- 函数,类,和类的实例(带警告)。
#coding:utf-8 #Filename:pickling.py ''' Created on 2012-2-27 @author: goodspeedcheng ''' import pickle as p shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple','mango','carrot'] #f = open(shoplistfile,'wb') #p.dump(shoplist,f) with open(shoplistfile,'wb') as f: p.dump(shoplist,f) f.close() del shoplist f = open(shoplistfile,'rb') storedlist = p.load(f) print(storedlist)
执行代码将会输出:
['apple','mango','carrot']
再次执行 只需执行
f = open(shoplistfile,'rb') storedlist = p.load(f) print(storedlist)
会输出同样的结果
最新版本的pickle协议是二进制格式的。请确认使用二进制模式来打开你的pickle文件,否则当你写入的时候数据会被损坏。
为了在文件里储存一个对象,首先以写模式打开一个file
对象,然后调用储存器模块的dump
函数,把对象储存到打开的文件中。这个过程称为 储存 。
作者:GoodSpeed Cheng
出处:http://www.cnblogs.com/cacique/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。