UnicodeDecodeError:“ ascii”编解码器无法解码位置中的字节:序数不在范围内(128)

Jus*_*n S 5 postgresql encoding utf-8 latin1 python-3.4

我已经对该错误进行了一些研究,无法真正了解发生的情况。据我了解,我基本上会遇到问题,因为我正在从一种编码类型转换为另一种编码类型。

def write_table_to_file(table, connection):
    db_table = io.StringIO()
    cur = connection.cursor()
    #pdb.set_trace()
    cur.copy_to(db_table, table)
    cur.close()
    return db_tabl
Run Code Online (Sandbox Code Playgroud)

这是给我头疼的方法。当我运行此方法时,输出以下错误

[u350932@config5290vm0 python3]$ python3 datamain.py 
Traceback (most recent call last):
  File "datamain.py", line 48, in <module>
    sys.exit(main())
  File "datamain.py", line 40, in main
    t = write_table_to_file("cms_jobdef", con_tctmsv64)
  File "datamain.py", line 19, in write_table_to_file
    cur.copy_to(db_table, table)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 40: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

从中检索表的数据库上的客户端编码为

tctmsv64=> SHOW CLIENT_ENCODING;
 client_encoding
-----------------
 sql_ascii
(1 row)
Run Code Online (Sandbox Code Playgroud)

数据库编码为LATIN1

我输入的数据库的编码是

S104838=# SHOW CLIENT_ENCODING;
 client_encoding
-----------------
 WIN1252
(1 row)
Run Code Online (Sandbox Code Playgroud)

数据库编码为UTF8

从我发现的线程中,他们建议更改编码

To correct your function, you'll have to know what encoding the byte
string is in, and convert it to unicode using the decode() method,
and compare that result to the unicode string.
Run Code Online (Sandbox Code Playgroud)

http://www.thecodingforums.com/threads/unicodedecodeerror-ascii-codec-cant-decode-byte-0xa0-in-position-10-ordinal-not-in-range-128.336691/

问题是当我尝试使用解码方法时,我抱怨它不是文件类型。我看过了io.StringIO(initial_value ='',newline ='\ n')¶类的python 3.4方法,但是在更改编码时找不到任何东西。

我还找到了概述问题的页面,但无法弄清楚解决该问题所需做的事情

https://wiki.python.org/moin/UnicodeDecodeError

基本上,我对正在发生的事情很困惑,不知道如何解决。任何帮助将不胜感激。

干杯

Cra*_*ger 3

Python 3 改变了围绕文本编码的文件 I/O 行为——在我看来,这是为了变得更好。您可能会发现《在 Python 3 中处理文本文件》内容丰富。

看起来psycopg2您传递了一个原始文件对象,并尝试将其正在使用的字符串编码为字节序列以写入文件,并假设(因为您没有指定其他任何内容)您想要使用ascii文件的编码。

我会使用一个io.BytesIO对象而不是StringIO,并在执行时指定源编码copy_from,并在您对新数据库

不过,如果您没有SQL_ASCII因源数据库中的无效、混合或其他错误文本而遇到问题,我会感到惊讶。