文件操作
fp = open("文件名","模式","字符编码集")
fp 文件的io对象 (文件句柄)
i : input 输入
o : output 输出
1.文件的写入操作
(1) 打开文件 (把冰箱门打开)
'''r"E:\python30\ceshi1.txt" 可以指定路径'''
fp = open("ceshi1.txt",mode="w",encoding="utf-8")
(2) 写入内容 (把大象塞进去)
fp.write("把大象塞进去")
(3) 关闭文件 (把冰箱门关上)
fp.close()
2.文件的读取操作
(1) 打开文件
fp = open("ceshi1.txt",mode="r",encoding="utf-8")
(2) 读取内容
res = fp.read()
print(res)
(3) 关闭文件
fp.close()
3.字节流的转换
二进制的字节流:用来传输或者存储的数据 bytes
b"123" 要求: b开头的字符串 ,内容必须是ascii编码
将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)
encode() 编码 将字符串转化为字节流(Bytes流)
decode() 解码 将Bytes流转化为字符串
strvar = "我爱你"
将字符串转化为字节流
res = strvar.encode("utf-8")
print(res)
将Bytes流转化为字符串
strvar2 = res.decode("utf-8")
print(strvar2)
len 算一下字节流的长度(一个字符是3个字节)
num = len(res)
print(num)
res = b"\xe7\x88\xb1".decode("utf-8")
print(res)
res = "我爱王二麻子,我永远是你得不到的男人"
print(res.encode("utf-8"))
4.存储字节流
wb 与 rb 来存储二进制字节流
1.打开文件
字节流模式下,无需指定编码集
fp = open("ceshi2.txt",mode="wb")
str_bytes = "我好想你,我的baby".encode("utf-8")
2.写入字节流
fp.write(str_bytes)
3.关闭文件
fp.close()
5.读取字节流
1.打开文件
字节流模式下,无需指定编码集
fp = open("ceshi2.txt",mode="rb")
2.读取字节流
res = fp.read()
3.关闭文件
fp.close()
print(res)
strvar = res.decode("utf-8")
print(strvar)
复制文件夹中 集合.png 这张图片
图片 音频 视频这样的文件都是二进制bytes
1.先把所有的二进制字节流读取出来
fp = open("集合.png",mode="rb")
str_bytes = fp.read()
fp.close()
print(str_bytes)
2.再把所有读出来的二进制字节流写入到另外一个文件中
fp = open("集合2.png",mode="wb")
fp.write(str_bytes)
fp.close()