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

python输入输出

2007-04-03 12:55 417 查看
对于输入输出操作,我们可以用raw_input或print语句实现,但我们也可以用文件来实现,下面我们将讨论文件的使用。

1、文件

我们可以用文件类来创建一个文件对象,并用它的read、readline、write方法实现文件的读写操作。当文件使用完毕后,你应该使用close方法,以释放资源。
下面是一个使用文件的例子:

#!/usr/bin/python
# Filename: using_file.py

poem = '''/
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''

f = file('poem.txt', 'w') #以写的方式打开文件poem.txt,返回一个文件句柄
以代表文件
f.write(poem) # 将poem中的文本写入文件
f.close() # 关闭打开的文件

f = file('poem.txt') # 没有指定打开文件的方式的时候,读模式是默认模式
while True:
line = f.readline()#一次读取一行
if len(line) == 0: # 读到文件结尾时终止
break
print line, # 逗号用于避免print自动分行
f.close()

输出如下:

$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

2、Pickle模块

Pickle模块用于将对象存储于文件中,需要时再将对象从文件中取出来。另外还有一模块cPickle,它的功能和Pickle一样,不同的是它是用c语言写的,并且速度更快。下面我们以cPickle为例介绍使用方法:

#!/usr/bin/python
# Filename: pickling.py

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data' # 存储对象的文件名
shoplist = ['apple', 'mango', 'carrot']
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # 存储对象到文件shoplist.data
f.close()

del shoplist

f = file(shoplistfile)
storedlist = p.load(f)#从文件中取出对象
print storedlist

输出结果:

$ python pickling.py
['apple', 'mango', 'carrot']


本系列的文章来源是http://www.pythontik.com/html,如果有问题可以与那里的站长直接交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: