【发布时间】:2012-02-01 04:44:31
【问题描述】:
您好,我有一个包含 unicode 字符的大文件,当我尝试在 Python 3 中打开它时,这是我遇到的错误。
文件“addRNC.py”,第 47 行,在 add_rnc()
文件“addRNC.py”,第 13 行,在 init 中 rawDoc.readline() 中的值:
文件“/usr/local/lib/python3.1/codecs.py”,第 300 行,在解码中 (结果,消耗) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError:“utf8”编解码器无法解码位置 158 中的字节 0xd3:无效的继续字节
我尝试了所有方法,但没有成功,代码如下:
rawDoc = io.open("/root/potential/rnc_lst.txt", 'r', encoding='utf8')
result = []
for value in rawDoc.readline():
if len(value.split('|')[9]) > 0 and len(value.split('|')[10]) > 0:
if value.split('|')[9] == 'ACTIVO' and value.split('|')[10] == 'NORMAL':
address = ''
for piece in value.split('|')[4:7]:
address += piece
if value.split('|')[8] != '':
rawdate = value.split('|')[8].split('/')
_date = rawdate[2]+"-"+rawdate[1]+"-"+rawdate[0]
else:
_date = 'NULL'
id = db.prepare("SELECT id FROM potentials_reg WHERE(rnc = '%s')"%(value.split('|')[0]))()
if len(id) == 0:
if _date == 'NULL':
db.prepare("INSERT INTO potentials_reg (rnc, _name, _owner, work_type, address, telephone, constitution, active)"+
"VALUES('%s', '%s', '%s', '%s', '%s', '%s', NULL, '%s')"%(value.split('|')[0], value.split('|')[1],
value.split('|')[2],value.split('|')[3],address,
value.split('|')[7], 'true'))()
else:
db.prepare("INSERT INTO potentials_reg (rnc, _name, _owner, work_type, address, telephone, constitution, active)"+
"VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"%(value.split('|')[0], value.split('|')[1],
value.split('|')[2],value.split('|')[3],address,
value.split('|')[7],_date, 'true'))()
else:
pass
db.close()
【问题讨论】:
-
是什么让您认为该文件是一个以 UTF-8 编码的 Unicode 文件?例如,字节 0xD3 是 MacRoman 编码中的 U+201D ʀɪɢʜᴛ ᴅᴏᴜʙʟᴇ Qᴜᴏᴛᴀᴛɪᴏɴ ᴍᴀʀᴋ。该文件是否验证为 UTF-8?
标签: python unicode python-3.x