python输入输出
2007-04-03 12:55
417 查看
对于输入输出操作,我们可以用raw_input或print语句实现,但我们也可以用文件来实现,下面我们将讨论文件的使用。
下面是一个使用文件的例子:
输出如下:
输出结果:
本系列的文章来源是http://www.pythontik.com/html,如果有问题可以与那里的站长直接交流。
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,如果有问题可以与那里的站长直接交流。
相关文章推荐
- python3精简笔记(一)-输入输出,类型,循环
- day2 python输入输出
- 20170726Python01_Python简介和输入输出
- 20170726Python01_Python简介和输入输出
- python的标准输入输出
- Python学习笔记 输入输出
- Python(基本输入输出)
- python的输入输出
- python输入输出
- python标准输入输出
- Python学习【2】基本输入输出语句
- python3之输入输出格式
- Python3的ACM输入输出格式
- 第17节--python的输入输出(IO)
- 【学习笔记】Python的输入输出
- 【Python专题】python入门之代码编辑器和输入输出
- ACM八大输入输出格式之Python版
- python基本语法_输入输出详解
- Python 学习之输入输出
- Python学习(二)——输入输出