我正在尝试使用Python将数据写入StringIO对象,最终使用psycopg2的copy_from()函数将该数据加载到postgres数据库中。起初我这样做时,copy_from()会抛出错误:ERROR: invalid byte sequence for encoding "UTF8": 0xc92,所以我遵循了this question。我发现我的Postgres数据库具有UTF8编码。我将要写入数据的文件/StringIO对象显示其编码如下:setgid Non-ISO extended-ASCII English text, with very long lines, with CRLF line terminators。我尝试将我写入到中间文件/StringIO对象的每个字符串都编码为UTF8格式。为此,我使用了.encode(encoding='UTF-8',errors='strict'))对每个字符串进行编码。现在我得到的错误是:UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 47: ordinal not in range(128)。这是什么意思?我该如何解决?编辑:我正在使用Python 2.7,代码的一些片段如下:
我从一个使用MySQL Workbench编码为UTF-8的MySQL数据库中读取数据。 以下是将我的数据(从MySQL数据库获取)写入StringIO对象的几行代码:
我从一个使用MySQL Workbench编码为UTF-8的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>)