python查看文件编码方式_如何知道Python中文件的编码?

1586010002-jmsa.png

Does anybody know how to get the encoding of a file in Python. I know that you can use the codecs module to open a file with a specific encoding but you have to know it in advance.

import codecs

f = codecs.open("file.txt", "r", "utf-8")

Is there a way to detect automatically which encoding is used for a file?

Thanks in advance

Edit:

Thanks everybody for very interesting answsers. You may also be interested by http://whatismyencoding.com/ which is based on chardet (more over the site is powered by bottle python framework)

解决方案

Unfortunately there is no 'correct' way to determine the encoding of a file by looking at the file itself. This is a universal problem, not limited to python or any particular file system.

If you're reading an XML file, the first line in the file might give you a hint of what the encoding is.

Otherwise, you will have to use some heuristics-based approach like chardet (one of the solutions given in other answers) which tries to guess the encoding by examining the data in the file in raw byte format. If you're on Windows, I believe the Windows API also exposes methods to try and guess the encoding based on the data in the file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值