#Python中os中编码encode与decode 解码

21.编码encode

import os 								#导入os 库
path = "C:\\Users\\Administrator\\Desktop\\新建文本文档.txt"
with open(path,"wb") as f1:
    f1.write(b"sunck is a good boy")
相当于
with open(path,"wb") as f1:
    str = "sunck is a good boy"
    f1.write(str.encode("utf-8"))
with open(path,"wb",encoding="utf-8") as f1:
#通过字节方式写入文件的时候,传给Python的必须是字节数据,否则就会报错:
#ValueError: binary mode doesn't take an encoding argument

22.decode 解码

import os 										#导入os 库
with open(path,"w",encoding="utf-8") as f3:
    str = "sunck is a good boy萨a德"
    f3.write(str)

with open(path,"r",errors= "ignore") as f4:		 #不写errors= "ignore" 此处也没报错
    data = f4.read()
    print(data)
    print(type(data))

猜你喜欢

转载自blog.csdn.net/weixin_43097301/article/details/82975631