当前位置: 移动技术网 > IT编程>脚本编程>Python > 【2020Python错题本】文件处理

【2020Python错题本】文件处理

2020年03月14日  | 移动技术网IT编程  | 我要评论

韩流来袭,榆林交通违章查询,超级塞伯坦系统

错误类型:

unicodedecodeerror: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence

1、 t 模式下的 读操作

 

新建txt文件 313.txt ——

hello world
hello day
hello me

@2020

 

>>> f=open(r'd:\0tempt\313.txt',mode='rt')
>>> print(f)
<_io.textiowrapper name='d:\\0tempt\\313.txt' mode='rt' encoding='cp936'>
>>> res=f.read()
>>> print(res)
hello world
hello day
hello mili

@2020

>>> 

 

新建txt文件 3133.txt——

你好,世界
你好,每一天
你好,米粒

 

>>> f=open(r'd:\0tempt\3133.txt',mode='rt')
>>> print(f)
<_io.textiowrapper name='d:\\0tempt\\3133.txt' mode='rt' encoding='cp936'>
>>> res=f.read()
traceback (most recent call last):
  file "<pyshell#46>", line 1, in <module>
    res=f.read()
unicodedecodeerror: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence
>>> 

unicodedecodeerror: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence

解决方法: 指定解码编码格式——encoding='utf-8'

>>> f=open(r'd:\0tempt\3133.txt',mode='rt',encoding='utf-8')
>>> print(f)
<_io.textiowrapper name='d:\\0tempt\\3133.txt' mode='rt' encoding='utf-8'>
>>> res=f.read()
>>> print(res)
你好,世界
你好,每一天
你好,米粒

>>> 

 

=====

之前英文和数字的文本内容,读取时没有指定解码编码,没有出错。是因为英文和数字是不会出现乱码现象的,使用任何编码类型解释器都能识别英文和数字。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网