`
BradyZhu
  • 浏览: 245391 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Python 初体验之 输入输出流

 
阅读更多

任何一个语言都有他的输入输出,对于文件的操作是非常有用的。在Java中曾经有对象序列化这么一个概念,在

Python中同样可以对对象进行序列化然后存放到文件中去,同时还能从文件中再读取出来,估计也可以像Java那样在网

络中进行传输。下面我们先来说一个简单的创建文件和读取文件的例子吧

'''
Created on 2013-2-3

@author: Administrator
'''
f = open("poem.txt","w")
f.write("haha")
f.close()

f = open("poem.txt","r")
while True:
    line = f.readline()
    if len(line)==0:
        break
    print(line)
f.close()
可以看到,这个例子使用open函数进行创建函数和读取函数,后面的w代表写入,r代表读取,还有a代表在末尾添加


下面我们在来说一个更加复杂点的例子,这个例子的主要功能就是把对象写入到文件中去的例子

'''
Created on 2013-2-3

@author: Administrator
'''
import pickle as p

shoplistfile = "shoplist.data"
shoplist=['apple','mango','carrot']

#write to the file
f = open(shoplistfile,"wb")
p.dump(shoplist,f)
f.close()

del shoplist

f = open(shoplistfile,"rb")
storedlist = p.load(f)
print(storedlist)

其实就是使用pickle这个模块里面的,dump函数进行把对象写入到文件中去,而load则是把对象从文件中读取出来

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics