Python自动判断文件的编码格式

问题

with open(path,'r') as f的时候出现:
在这里插入图片描述
或者在with open(path,'r',encoding='utf-8') as f
在这里插入图片描述
等等,最好的方法是先判断一下文件的编码,然后‘对症下药’

解决办法

直接丢一个函数先判断一下文件的编码方式:

import chardet
def get_file_encoding(path):
    with open(path,'rb') as f:
        text = f.read()
    file_encoding = chardet.detect(text)['encoding']
    return file_encoding

然后在真正读取文件的时候指定该函数返回的编码为open的编码方式

open(path,'rb',encoding=get_file_encoding(path)) as f:
    f# 问题

在`with open(path,'r') as f`的时候出现:

![在这里插入图片描述](https://img-blog.csdnimg.cn/8ff6390d12a24d829ab620d1a2e6542a.png)
或者在`with open(path,'r',encoding='utf-8') as f`

![在这里插入图片描述](https:img-blog.csdnimg.cn/4220529e2f9547c7866c0f275ec10286.png)
Wait, the best way is to judge the encoding of the file first, and then 'get it right'


# Workaround

Drop a function directly to judge the encoding of the file first:


```python
import chardet
def get_file_encoding(path):
    with open(path,'rb') as f:
        text = f.read()
    file_encoding = chardet.detect(text)['encoding']
    return file_encoding

Then specify the encoding returned by the function as open encoding when the file is actually read

open(path,'rb',encoding=get_file_encoding(path)) as f:
...

成功解决!

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值