Python Tik
首页
编程基础

基本数据类型
操作符和表达式
控制语句的执行顺序
函数
模块
数据结构

输入输出
异常处理
标准库概要

Python应用

网络应用
数据库应用
图形用户界面开发
游戏开发

Python交流

博客

Python论坛

输入输出

上一页 下一页

对于输入输出操作,我们可以用raw_input或print语句实现,但我们也可以用文件来实现,下面我们将讨论文件的使用。

1、文件

我们可以用文件类来创建一个文件对象,并用它的read、readline、write方法实现文件的读写操作。当文件使用完毕后,你应该使用close方法,以释放资源。
下面是一个使用文件的例子:
#!/usr/bin/python
#-*- encoding:UTF-8 -*-
# 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() raw_input('(按任意键结束)')
输出如下:
$ 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
#-*- encoding:UTF-8 -*-
# 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
raw_input('(按任意键结束)')
输出结果:
$ python pickling.py
['apple', 'mango', 'carrot']
(按任意键结束)

上一页 下一页

版权所有
联系方式 email:zzjcs1971@163.com QQ:397987442