import sys, os, chardet
files = [
'utf8.txt',
'gb2312.txt',
]
for filename in files:
# 采样长度,最长采样长度为100,可调节
sample_len = min( 100, os.path.getsize( filename))
#读取片段bytes
raw = open( filename, 'rb').read( sample_len)
#检测编码
detect = chardet.detect( raw)
with open( filename, 'r+', encoding=detect['encoding'], errors='ignore') as fp:
pass
Python打开不同编码文件
最新推荐文章于 2023-06-20 13:34:41 发布
本文介绍了一种使用Python实现的文件编码检测方法,通过chardet库检测文件的编码类型,并根据检测结果打开文件。该方法可以处理不同编码类型的文件,如utf8和gb2312等。
588

被折叠的 条评论
为什么被折叠?



