汪晓康

导航

python读取任意编码格式的文本

前言

有的时候默认使用utf8格式来读取文本,会导致报错。
如果对性能没有要求,可以在读取前使用chartdet库来判断文本编码。

代码示例

import chardet

def get_code(file_path):
    with open(file_path, 'rb') as f:
        data = f.read()
        result = chardet.detect(data)
        f.close()
    return result.get("encoding", None)
		
file_path = r"C:\Users\Desktop\track.txt"
encode_type = get_code(file_path)  

with open(file_path, 'r', encoding=encode_type) as read_file:
	lines = read_file.readlines()

posted on 2023-11-02 16:02  汪晓康  阅读(19)  评论(0编辑  收藏  举报