一批txt文档,有多种编码方式,怎么读取呢?
- 通过
chardet.detect()
检测出文本的编码方式 open
时设置encoding
import chardet
# 假设有一个名为 'file_path' 的文件路径
with open(file_path, 'rb') as f:
data = f.read()
result = chardet.detect(data) # 检测文件编码
encoding = result['encoding'] # 获取检测到的编码格式
with open(file_path, 'r', encoding=encoding) as f:
content = f.read()