一批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()
本文介绍了如何使用Python的chardet库检测txt文件的编码类型,然后根据检测结果正确地打开和读取文件内容。
4222

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



