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))