程序与用户的基本交互通常使用raw_input和print。
文件
对于文件,需要创建、读写功能。可以通过创建一个file类的对象来打开一个文件,分别使用file类的read、readline、write方法恰当的读写文件。对文件的读写能力依赖于在打开文件时指定的模式。当完成文件的操作后,调用close方法。
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'
)、写模式('w'
)或追加模式('a'
)。
储存器
标准模块pickle(或者cPickle,使用c语言编写,速度快),可以使用这个模块在一个文件中储存任何python对象,之后完整无缺的取出来,被称为持久地储存对象。
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']
dump函数,把对象储存到打开的文件中,这个过程称为 存储。
使用load函数返回取回的对象,这个过程称为 取储存。