【发布时间】:2016-07-25 13:46:54
【问题描述】:
我正在尝试读取文件并将字符串转换为UTF-8 字符串,以便删除文件字符串中的一些非utf-8 字符,
file_str = open(file_path, 'r').read()
file_str = file_str.decode('utf-8')
但我收到以下错误,
AttributeError: 'str' object has no attribute 'decode'
更新:我尝试了答案建议的代码,
file_str = open(file_path, 'r', encoding='utf-8').read()
但它并没有消除非utf-8 字符,那么如何删除它们呢?
【问题讨论】:
-
您使用的是 python 3 吗?在这种情况下,所有字符串都已经是 unicode 对象。你不需要解码。
-
您使用的是 Python 3;
open()返回了一个已为您解码为 Unicode 的文件对象。 Python 3str是 Unicode 类型,它没有decode()方法,因为您无法进一步解码 Unicode。 -
对于编码问题...请务必提及 Python 版本或相应地标记它..
标签: python python-3.x utf-8 decode