python decode() encode() seek()
"我".encode() 是将"我"转变成bytes输出
b'\xe6\x88\x91'.decode() 是将bytes转变成字符串"我"

例如:
文件12.txt,内容都为中文
file = open("12.txt","rb+") 以bytes方式打开文件
file.readline()
所有的中文输出为:\xce\xb4\xd7.......
我们使用:
file.readline().decode("gbk")
即可将bytes类型转换为中文
只有使用rb打开一个文件的使用,seek(4,1)才能使用
seek(偏移量,0/1/2)
:seek(N,0) 移动到绝对位置N
:seek(N,1) 从当前位置向后移动N(使用r打开一个文件,该条相对位置移动报错)
:seek(0,2)移动到文件的末尾
以下使用IPYTHON测试的
In [240]: file.seek(-11,1) Out[240]: 420 # 移动到420位置 In [241]: file.readline().decode("gbk") Out[241]: ' 加入清单\r\n' # 输出的内容 In [243]: file.seek(421) Out[243]: 421 # 移动到421位置 In [244]: file.readline().decode("gbk") Out[244]: '加入清单\r\n' # 输出的内容,少了一个空格 In [245]: file.seek(422) Out[245]: 422 # 移动到422位置 In [246]: file.readline().decode("gbk") --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-246-c4850faa0bd6> in <module>() ----> 1 file.readline().decode("gbk") UnicodeDecodeError: 'gbk' codec can't decode byte 0xa5 in position 6: illegal mu ltibyte sequence # 输出报错 In [247]: file.seek(423) Out[247]: 423 # 移动到423位置 In [248]: file.readline().decode("gbk") Out[248]: '入清单\r\n' # 输出内容少一个"加"
因此使用seek定位中文字符文件的时候,中文一个字符要当两个位置来使用

浙公网安备 33010602011771号