我想用Python编写一个StringIO对象中的数据,然后最终使用psycopg2将这些数据加载到postgres数据库中copy_from()函数。UnicodeDecodeError:'ascii'编解码器无法解码位置47中的字节0x92:序号不在范围内(128)
首先当我这样做时,copy_from()引发错误:ERROR:编码“UTF8”的无效字节序列:0xc92所以我遵循this question。
我发现我的Postgres数据库有UTF8编码。
文件/ StringIO对象,我写我的数据转换成显示出其作为下面的编码: setgid的非ISO扩展ASCII英文文本,有很长的线,CRLF行终止
我试图编码每一个我正在写入中间文件/ StringIO对象的字符串转换为UTF8格式。为每个字符串使用.encode(encoding ='UTF-8',errors ='strict'))。
这是我现在得到了错误: 的UnicodeDecodeError:在47位“ASCII”编解码器不能解码字节0x92:有序不在范围内(128)
是什么意思?我如何解决它?
编辑: 我使用Python 2.7 我的一些代码片段:
我从在UTF-8编码为每MySQL工作台数据MySQL数据库读取。 这是写我的数据的几行代码(这是从MySQL数据库获得)中,StringIO对象:
# Populate the table_data variable with rows delimited by \n and columns delimited by \t
row_num=0
for row in cursor.fetchall() :
# Separate rows in a table by new line delimiter
if(row_num!=0):
table_data.write("\n")
col_num=0
for cell in row:
# Separate cells in a row by tab delimiter
if(col_num!=0):
table_data.write("\t")
table_data.write(cell.encode(encoding='UTF-8',errors='strict'))
col_num = col_num+1
row_num = row_num+1
这是从我的StringIO对象TABLE_DATA写入Postgres数据库的代码:
cursor = db_connection.cursor()
cursor.copy_from(table_data, <postgres_table_name>)
请显示您的代码 – 2014-10-28 23:17:13
您使用的是哪种MySQL包装? – abarnert 2014-10-28 23:59:49
此外,不是显示“我的代码的某些部分”,而是创建一个自包含的[最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)并在此处发布。 – abarnert 2014-10-29 00:02:26