【python自学】(八)-----输入/输出 文件

程序与用户的基本交互通常使用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函数返回取回的对象,这个过程称为 取储存。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值