python 输入输出

大城市里の小女人 提交于 2020-01-14 03:24:33

先看一个例子

#coding:utf-8
#Filename:using_flie.py
'''
Created on 2012-2-27
@author: goodspeedcheng
'''
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''

f = open('poem.txt','w',encoding='utf-8')
f.write(poem)
f.close()

r = open('poem.txt')
while True:
    line = r.read()
	#line = r.readline()
	#line = r.readlines()
    if len(line) == 0:
        break
    print(line)
r.close() 

>>>line = r.read()

输出结果为

Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!

>>>line = r.readline()     

输出结果为

Programming is fun

When the work is done

if you wanna make your work also fun:

        use Python!

>>>line = r.readlins()

输出结果为

['Programming is fun\n', 'When the work is done\n', 'if you wanna make your work also fun:\n', '        use Python!\n']

 

储存器

Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

什么东西能用pickle模块存储?

  • 所有Python支持的 原生类型 : 布尔, 整数, 浮点数, 复数, 字符串, bytes(字节串)对象, 字节数组, 以及 None.
  • 由任何原生类型组成的列表,元组,字典和集合。
  • 由任何原生类型组成的列表,元组,字典和集合组成的列表,元组,字典和集合(可以一直嵌套下去,直至Python支持的最大递归层数).
  • 函数,类,和类的实例(带警告)。
#coding:utf-8
#Filename:pickling.py
'''
Created on 2012-2-27
@author: goodspeedcheng
'''
import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple','mango','carrot']

#f = open(shoplistfile,'wb')
#p.dump(shoplist,f)
with open(shoplistfile,'wb') as f:
    p.dump(shoplist,f)
f.close()

del shoplist
f = open(shoplistfile,'rb')
storedlist = p.load(f)
print(storedlist)

执行代码将会输出:

['apple','mango','carrot']

再次执行 只需执行

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

会输出同样的结果

最新版本的pickle协议是二进制格式的。请确认使用二进制模式来打开你的pickle文件,否则当你写入的时候数据会被损坏。

为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!