MST

星途 面试题库

面试题:Python字符串编码转换之常见场景

在Python中,假设你从文件读取了一段内容,文件声明编码为UTF - 8,但实际内容可能包含一些错误编码的字符。请编写代码处理这种情况,将内容正确转换为Unicode字符串,并捕获可能的编码错误,打印出错误信息。
46.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
try:
    with open('your_file.txt', 'rb') as f:
        content = f.read()
        try:
            # 先尝试用UTF - 8解码
            decoded_content = content.decode('utf-8')
        except UnicodeDecodeError:
            # 如果失败,用 'ignore' 错误处理方式进行解码
            decoded_content = content.decode('utf-8', 'ignore')
            print("存在编码错误,已忽略错误字符进行解码。")
    print("转换后的Unicode字符串:", decoded_content)
except FileNotFoundError:
    print("文件未找到。")