Python_7:IO流和对象序列化

一、基本概念

1.1 什么是IO流

IO流(input output stream)主要指的是计算机的输入和输出操作。常见的IO操作,一般说的是内存与磁盘之间的输入输出,IO流操作一种常见的持久化技术。

1.2 Python的IO流_open()

open函数主要的目的是打开一个本地的文件

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.

#mode参数
 ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================

1.2.1 open()的简单使用

f = open(path, "r")
msg = f.read()

# 最后关闭IO流
f.close()

1.3 IO流的分类

1.3.1根据数据流动方向

  • 输入流 读操作 mode=‘r’
  • 输出流 写操作
    • mode=‘w’ 覆盖写入
    • mode=‘a’ 追加写入(文件存在)

1.3.2根据数据的类型

  • 字符流 mode=‘t’

  • 字节流 mode=‘b’

    字节流操作大数据时,不建议一次性读取

1.3.3根据上述分类可以结合使用:

  • mode=‘rt’/‘tr’ 字符输入流
  • mode='rb 字节输入流
  • mode=‘wt’ 字符输出流
  • mode=‘wb’ 字节输出流

二、IO流对象的常用方法

f = open(file, “r”) # f就是python IO对象

  • read(sieze=-1) #读取

    size为索引,-1代表索引中的最后一个。默认该方法将整个文件读取完(从下标0读到-1)

    • 字节流读到末尾:“”

    • 字符流读到末尾:b""

      字节流操作大数据时,不建议一次性读取

  • write(data) #写入到文件

  • writelines() #多行写入,参数可以是容器

  • flush() #刷新缓存区

  • close() #关闭IO对象,close()会自动的调用flush()进行最后的文件刷新

#几个问题
>>> f1
<_io.TextIOWrapper name='f:\\a.txt' mode='r' encoding='utf-8'>

#1、下标问题,read()方法随着下标在读取文件
>>> f1.read(2)
'今天'
>>> f1.read()
'也要加油啊!'
>>> f1.read()
''

#2、缓冲区问题
>>> f2 = open('f:\\b.txt','w',encoding='utf-8')
>>> f2.write("你好")
2
#此时查看f2文件并没有写入信息,写入信息存在于缓冲区中。需要执行flush()或者close()方法。

#3、循环结构读字符文件
def cycle(soc):
	f1 = open(soc,mode='tr',encoding='UTF-8')
	
	for i in f1:
		print(i)
		print("~" *50)

	f1.close()

source = input("原文件绝对路径:")
cycle(source)
#此时循环变量i是文件中的每一行
#结果:
"""
D:\Python\project>16读文件.py
原文件绝对路径:f:\a.txt
OSPF

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OSPF(Open Shortest Path First)开放式最短路径优先算法          无类别链路状态型路由协议

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      适用范围:IGP
"""

三、备份文件

3.1 字符流

#备份字符文件
def txt_copy(soc,des):
	f1 = open(soc,mode='tr',encoding='UTF-8')
	f2 = open(des,mode='w',encoding='UTF-8')
	msg = f1.read()                    #一次性读完
	f2.write(msg)
    #f2.write(f1.read())
	f1.close()
	f2.close()
source = input("原文件绝对路径:")
destination = input("备份文件路径:")
txt_copy(source,destination)

3.2 字节流

#备份大文件(字节流形式)
def copy_file(src,des):
	f1 = open(src,"br")
	f2 = open(des,"bw")

	while True:
		data =  f1.read(1024*1024)		#控制每次读写的大小
		if 	data == b"":                #字节流的末尾
			break
		f2.write(data)
	print("copy完成")

	f1.close()
	f2.close()

source = input("原文件绝对路径:")
destination = input("备份文件路径:")
copy_file(source,destination)

四、对象序列化

4.1 什么是对象序列化

将内存中的一个抽象概念、逻辑概念(对象)转换成字节或者字符数据的过程,就叫做对象序列化

4.2 pickle模块

将对象转换为字节数据

  • dump # 将对象序列化成为字节数据,并且保存到file中

    dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

  • dumps # 将对象序列化成为字节数据

    dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)

  • load # 将一个file对象反序列化为对象

  • loads # 将一个字节数据反序列化为对象

>>> import pickle

>>> ls = [1,2,3,4,5]

#将列表ls序列化为
>>> pickle.dumps(ls)
b'\x80\x04\x95\x0f\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03K\x04K\x05e.'

>>> data = pickle.dumps(ls)
>>> f = open("f:\\p.dat","wb")
>>> f.write(data)
26
>>> f.close()

>>> f = open("f:\\p.dat","rb")
>>> show = f.read()

>>> show
b'\x80\x04\x95\x0f\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03K\x04K\x05e.'

#反序列化
>>> pickle.loads(show)
[1, 2, 3, 4, 5]

4.3 json模块

将对象转换为字符数据

json一般用来序列化字典对象,或者转换json数据,但是其他对象也是可以的

  • dump # 将对象序列化成为字符数据,并且保存到file中
  • dumps # 将对象序列化成为字符数据
  • load # 将一个file对象反序列化为对象
  • loads # 将一个字符数据反序列化为对象
>>> d = {"username":"wang","gener":"male"}
>>> import json

>>> data = json.dumps(d)
>>> data
'{"username": "wang", "gener": "male"}'

>>> dic = json.loads(data)
>>> dic
{'username': 'wang', 'gener': 'male'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值