使用 psycopg2 编码复制到 PostgreSQL
PostgreSQL copy to with encoding using psycopg2
我正在从远程数据库中获取数据,并尝试使用 UTF8 编码将其写入 CSV 文件。
这就是我现在拥有的:
query = "select * from hotels limit 50000"
output_query = "copy ({0}) to stdout with csv header ecnoding 'UTF8'".format(query)
filename = "hotels.csv"
with open(filename, 'w') as f:
cur.copy_expert(output_query, f)
但这通常会抛出:
UnicodeEncodeError: 'charmap' codec can't encode character '\u016f' in position 52: character maps to <undefined>
如果我将查询限制更改为假设 1000 提到的异常不会发生,但如果我尝试使用 pandas 加载生成的 csv 文件,则会发生以下异常:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 14: invalid continuation byte
你知道问题出在哪里吗?如何以正确的方式将 sql table 导出到 csv?
提前致谢!
我应该在打开功能中添加encoding='utf-8'
。
我正在从远程数据库中获取数据,并尝试使用 UTF8 编码将其写入 CSV 文件。 这就是我现在拥有的:
query = "select * from hotels limit 50000"
output_query = "copy ({0}) to stdout with csv header ecnoding 'UTF8'".format(query)
filename = "hotels.csv"
with open(filename, 'w') as f:
cur.copy_expert(output_query, f)
但这通常会抛出:
UnicodeEncodeError: 'charmap' codec can't encode character '\u016f' in position 52: character maps to <undefined>
如果我将查询限制更改为假设 1000 提到的异常不会发生,但如果我尝试使用 pandas 加载生成的 csv 文件,则会发生以下异常:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 14: invalid continuation byte
你知道问题出在哪里吗?如何以正确的方式将 sql table 导出到 csv? 提前致谢!
我应该在打开功能中添加encoding='utf-8'
。