吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2095|回复: 2
收起左侧

[Python 转载] 解决python下的编码问题

[复制链接]
silentteamo 发表于 2019-3-8 12:15


python下不知道什么时候就会报编码错误,走一波,试试效果如何。

[Python] 纯文本查看 复制代码
import os
import codecs
# 读取文本文件函数,支持bom-utf-8,utf-8,utf-16,gbk,gb2312
# 返回文件内容
def ReadTextFile(filepath):
    try:
        file = open(filepath, 'rb')
    except IOError as err:
        print('读取文件出错 in ReadFile', err)
    bytes = file.read()
    file.close()
    if bytes[:3] == codecs.BOM_UTF8:
        content = bytes[3:].decode('utf-8')
    else:
        try:
            content = bytes.decode('gb2312')
        except UnicodeDecodeError as err:
            try:
                content = bytes.decode('utf-16')
            except UnicodeDecodeError as err:
                try:
                    content = bytes.decode('utf-8')
                except UnicodeDecodeError as err:
                    try:
                        content = bytes.decode('gbk')
                    except UnicodeDecodeError as err:
                        content = ''
                        print('不支持此种类型的文本文件编码', err)
    return content

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

ppff931111 发表于 2019-3-8 12:54
你这。。。如果打开的时候报错的话,打开的错误被处理了,但是后面的read还是会报错,因为你没有拿到文件句柄,还有打开文件用with吧
珍珠奶茶丶板牙 发表于 2019-3-8 13:15
你这根本就是弟弟操作呀

with open("your_file", 'rb') as fp:
    file_data = fp.read()
    result = chardet.detect(file_data)
    file_content = file_data.decode(encoding=result['encoding'])
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-7 23:09

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表