python编码与解码

文件打开编码

当创建文件,设定文件encoding编码时,打开文件也必须以相同的encoding值进行解码。

with open(path, "w", encoding = "utf-8") as f:
    f.write("Hello World!")

with open(path, "r", encoding = "utf-8") as f:    # 读取的编码模式应与写入一样
    f.read()
    

二进制打开编码

当文件以二进制打开时,必须对写入内容进行编码。读取文件时,则必须以相同的格式解码。

with open(path, "wb") as f:
    str = "Hello Word!"
    f.write(str.encode("utf-8"))    # 二进制文件写入必须设定编码

with open(path, "rb") as f:
    str = f.read()
    print(str.decode("utf-8"))    # 二进制文件读取必须进行解码

猜你喜欢

转载自blog.csdn.net/u010378984/article/details/82766835
今日推荐