【Python】输入输出字符串编码格式和文件读取写入编码格式

本文最后更新于:2023年6月12日 晚上 18:47

1 encode()和decode()方法:字符串编码转换

前言

Python 3.x 默认采用 UTF-8 编码格式,有效地解决了中文乱码的问题。

在 Python 中,有 2 种常用的字符串类型,分别为 str 和 bytes 类型,其中 str 用来表示 Unicode 字符,bytes 用来表示二进制数据。str 类型和 bytes 类型之间就需要使用 encode() 和 decode() 方法进行转换。

encode()方法

encode() 方法为字符串类型(str)提供的方法,用于将 str 类型转换成 bytes 类型,这个过程也称为“编码”。

encode() 方法的语法格式如下:

1
str.encode([encoding="utf-8"][,errors="strict"])

注意,格式中用 [] 括起来的参数为可选参数,也就是说,在使用此方法时,可以使用 [] 中的参数,也可以不使用。

该方法各个参数的含义如表 1 所示。

参数 含义
str 表示要进行转换的字符串。
encoding = "utf-8" 指定进行编码时采用的字符编码,该选项默认采用 utf-8 编码。
例如,如果想使用简体中文,可以设置 gb2312。
当方法中只使用这一个参数时,可以省略前边的“encoding=”,直接写编码格式,例如 str.encode("UTF-8")。
errors = "strict" 指定错误处理方式,其可选择值可以是:
strict:遇到非法字符就抛出异常。
ignore:忽略非法字符。
replace:用“?”替换非法字符。
xmlcharrefreplace:使用 xml 的字符引用。
该参数的默认值为 strict。

注意,使用 encode() 方法对原字符串进行编码,不会直接修改原字符串,如果想修改原字符串,需要重新赋值。

encode后的数据如下:

1
2
3
b'\xce\xd2\xca\xc7\xcb\xad'
b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81'
b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81'

decode()方法

和 encode() 方法正好相反,decode() 方法用于将 bytes 类型的二进制数据转换为 str 类型,这个过程也称为“解码”。

decode() 方法的语法格式如下:

1
bytes.decode([encoding="utf-8"],[errors="strict"])

该方法中各参数的含义如表 2 所示。

参数 含义
bytes 表示要进行转换的二进制数据。
encoding="utf-8" 指定解码时采用的字符编码,默认采用 utf-8 格式。
当方法中只使用这一个参数时,可以省略“encoding=”,直接写编码方式即可。
errors = "strict" 指定错误处理方式,其可选择值可以是:
strict:遇到非法字符就抛出异常。
ignore:忽略非法字符。
replace:用“?”替换非法字符。
xmlcharrefreplace:使用 xml 的字符引用。
该参数的默认值为 strict。

encode()和decode()组合使用

Python中,从控制台输入字符串,会先被重编码为Python解释器默认的字符串格式(一般为UTF-8),所以可以不用管控制台的代码页格式。

想要重新编码,可采用以下方法:

注意encode和decode中的编码格式必须保持一致!

1
2
3
4
5
6
# 注意encode和decode中的编码格式必须保持一致!
# encode将str转化为byte,decode把byte转化为str,其中只有encode发挥了转换编码的作用,decode只是把encode输出的byte序列切分为str
str = str.encode("gbk").decode("gbk")
str = str.encode("utf-8").decode("utf-8")
str = str.encode(sys.stdin.encoding).decode(sys.stdin.encoding)
# sys.stdin.encoding可以查看Python解释器默认的字符串格式

sys.stdin.encoding可以查看Python解释器默认的字符串格式

2 文件读取写入编码格式

查看python默认读写文件的编码

在Python中,默认的输出编码通常与默认的文件编码是相同的,因为默认情况下,标准输出(stdout)被重定向到控制台或终端设备,其编码通常与系统的默认编码相同。

要查看Python默认输出编码,你可以使用sys.stdout.encoding

要查看Python默认文件编码,你可以使用locale.getpreferredencoding()

1
2
3
4
5
6
7
8
9
import sys
import locale

default_output_encoding = sys.stdout.encoding
default_file_encoding = locale.getpreferredencoding()

print("默认输出编码:", default_output_encoding)
print("默认文件编码:", default_file_encoding)

想要指定编码,只需要指定encoding即可。

1
2
3
4
5
6

with open(os.path.join(sys.path[0], name + ".txt"), "r", encoding="utf-8") as f:
data = f.readlines()

with open(os.path.join(sys.path[0], name + "_sorted.txt"), "w", encoding="utf-8") as f:
f.writelines(data)

【Python】输入输出字符串编码格式和文件读取写入编码格式
https://qalxry.github.io/2023/06/12/【Python】输入输出字符串编码格式和文件读取写入编码格式/
作者
しずり雪
发布于
2023年6月12日
更新于
2023年6月12日
许可协议