Python读写txt文件时的编码问题

import chardet

def get_encoding(filename): # 二进制方式读取,获取字节数据,检测编码类型
    with open(filename, 'rb') as f:
        return chardet.detect(f.read())['encoding']

def file_read(filename,file_code): #以文件编码类型读取文件
    with open(filename, 'r',encoding=file_code,errors="ignore") as file_to_read:
        file_content = file_to_read.read()
    return  file_content

if __name__ == '__main__':
    filename='0001.txt'
    file_code=get_encoding(filename)
    print(file_code)
    print(file_read(filename,file_code))

posted on 2019-06-24 16:35  sdlyxyf  阅读(234)  评论(0编辑  收藏  举报

导航