您现在的位置: IT技术文档中心 >> 文档资源 >> 编程语言及开发环境 >> Python >> 文档正文
Python编程基础(输入输出)
作者:未知 文章来源:互联网 点击数: 更新时间:2007-7-20 23:54:27

对于输入输出操作,我们可以用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']
网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)
| 设为首页 | 加入收藏 | 联系站长 | 版权申明 | 雁过留声 | 会员中心 |