- raw_input和print语句
对于输出,可以使用多种多样的str(字符串)类。例如,能够使用rjust方法来得到一个按一定宽度右对齐的字符串。利用help(str)获得更多详情
- 输入/输出类型是处理文件。
创建、读和写文件的能力是许多程序所必需的
文件
创建一个file类的对象来打开一个文件,
分别使用file类的read、readline或write方法来恰当地读写文件。
对文件的读写能力依赖于你在打开文件时指定的模式。模式可以为读模式('r')、写模式('w')或追加模式('a')
最后,当你完成对文件的操作的时候,调用close方法来告诉Python我们完成了对文件的使用
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提供一个标准的模块,称为pickle。
使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象
另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)
储存 and 取储存
#filename:pickling.py
import cPickle as p
#import Pickle as p
shoplistfile='shoplist.data'
shoplist=['apple','mango','crrot']
f=file(shoplistfile,'w')
p.dump(shoplist,f)
f.close
del shoplist
f=file(shoplistfile)
storedlist=p.load(f)
print storedlist
以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存
使用pickle模块的load函数的返回来取回对象。这个过程称为 取储存 。