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

A Byte of Python 笔记(10)输入/输出:文件和储存器

2016-04-06 17:38 791 查看
第12章 输入/输出

大多数情况下,我们需要程序与用户交互。从用户得到输入,然后打印一些结果。

可以分别使用 raw_input 和 print 语句来完成这些功能。对于输出,可以使用多种多样的 str(字符串)类。

另一个常用的输入/输出类型是处理文件。创建、读和写文件的能力是许多程序所必须的。

文件

通过 file 类的对象来打开一个文件,使用 file 类的 read、readline 或 write 方法来恰当地读写文件。对文件的读写能力依赖于打开文件时指定的模式(模式可以为读模式('r')、写模式('w')或追加模式('a'))。最后完成对文件的操作时,调用 close 方法完成对文件的使用。

# -*- coding: 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') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default

while True:
line = f.readline()
if len(line) == 0: # zero length indicates EOF
break
print line, # notice comma to avoid automatic newline added by Python

f.close()






首先,使用写模式打开文件,然后使用 file 类的 write 方法来写文件,最后用 close 关闭文件。

接下来,再一次打开同一个文件来读文件。如果不指定模式,默认为读模式。readline 方法读取文件的每一行,返回包括行末换行符的一个完整行。当一个空的字符串被返回时,表示文件末已经到达。

最后,使用 close 关闭这个文件。文件读到的内容已经以换行符结尾,所以在 print 语句上使用逗号消除自动换行。

储存器

python 提供一个标准的模块 pickle。可以在文件中储存任何 python 对象,之后可以把它完整无缺地取出来,被称为 持久地 储存对象。

另一个 cPickle,功能和 pickle 模块完全相同,用 C 语言编写,比 pickle 快1000倍。

# -*- coding: utf-8 -*-
# Filename: using_pickling.py

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple','mango','carrot']

# write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist






首先,使用 import..as 语法,以便于使用更短的模块名称。

储存 过程:首先以写模式打开一个 file 对象,然后调用储存器模块的 dump 函数把对象储存到打开的文件中。

取储存 过程:使用 pickle 模块的 load 函数的返回来取回对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: