温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中,关于读取文件编码解码的问题

发布时间:2020-06-21 13:47:19 来源:网络 阅读:1494 作者:田头草 栏目:编程语言

UnicodeDecodeError: 'gbk' codec can't decode byte 0xb1 in position 94: illegal multibyte sequence

            有时候用open()方法打开文件读取文件的时候会出现这个问题:‘GBK’编×××无法解码94号位置的字节0xb1:非法多字节序列。错误信息提示了使用“GBK”解码。
            1.分析
            pycharm自动使用的是‘UTF-8’编码,好像没有什么问题,为什么会出现这个错误呢。结果查了下open()函数的注解,里面又这么一段话:
             encoding is the name of the encoding used to decode or encode the  file. This should only be used in text mode. *The default encoding is platform dependent*, but any encoding supported by Python can be  passed.  See the codecs module for the list of supported encodings.
                 The default encoding is platform dependent:默认编码方式取决于平台。这也就不奇怪会用‘GBK’编码了,平台不一样,编码方式不一样,所以读取的时候回出现错误。
            2.解决方法
                    # 1.以byte读取,并以‘utf-8’解码
                    # fp = open(filename, 'rb')
                    # content = fp.read()
                    # self.content = content.decode('utf-8')
                    # fp.close()
                    # 2.在打开文件时指定编码方式
                    fp = open(filename, encoding='utf-8')
                    content = fp.read()
                    self.content = content
                    fp.close()

                    如有不同见解,欢迎分享。
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI