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

Python读书笔记第十一章:输入/输出

2014-02-28 10:35 232 查看
1.文件

程序与用户交互时,可以使用raw_input和print语句来完成这些功能。rjust可以得到一个按一定宽度右对齐的字符串。

通过创建一个file类的对象来打开一个文件,分别使用read、readline或write方法来读写文件。对文件的读写能力依赖于你在打开文件时指定的模式,最后通过调用close方法来告诉Python完成对文件的使用。

#!/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') # 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() # close the file
输出:

$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
模式可以为‘r’(read), 'w'(write), 'a'(append),此外还有很多的模式可以使用。

程序首先用w模式打开文件,然后使用write方法来写文件,最后使用close关闭这个文件。

如果没有指定模式,读模式会作为默认模式。在一个循环中,使用readline方法来读每一行。这个方法返回包括行末换行符的一个完整行。因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用都好来消除自动换行。

2.存储器

Python的pickle模块可以让你在一个文件中储存任何Python对象,之后你又可以完整无缺地取出来。这被成为持久地储存对象。与Pickle相同的还有一个cPickle模块(用C语言编写,速度快1000倍)。

#!/usr/bin/python
# Filename: 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
输出:

$ python pickling.py
['apple', 'mango', 'carrot']
使用import...as语法以便于我们可以使用更短的模块名称。为了在文件里储存一个对象,调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为储存。然后使用load函数返回来取会对象,这个过程称为取储存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐