如何使用Python以正确的字符编码读取SQL文件?

DPS*_*ial 5 python postgresql psycopg2

基于几个例子(这里这里),我可以使用 psycopg2 读取并希望从 python 运行 SQL 文件(该文件有 200 行,虽然运行速度很快,但不是我想在 python 文件中维护的内容) 。

\n\n

这是读取和运行该文件的脚本:

\n\n
sql = open("sql/sm_bounds_current.sql", "r").read()\n\ncurDest.execute(sql)\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,当我运行脚本时,会引发以下错误:

\n\n
Error: syntax error at or near "\xc3\xaf\xc2\xbb\xc2\xbfdrop"\nLINE 1: \xc3\xaf\xc2\xbb\xc2\xbfdrop table dpsdata.sm_boundaries_current_dev;\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如您所看到的,脚本中的第一行是删除一个表,但我不确定为什么要读取额外的字符,并且似乎找不到可能设置文件编码的解决方案阅读时。

\n

DPS*_*ial 5

发现这篇文章涉及编码和字节顺序标记,这就是我的问题所在。

解决方案是从 CODECS 导入 OPEN,这允许在 OPEN 上使用 ENCODING 选项:

import codecs
from codecs import open

sqlfile = "sql/sm_bounds_current.sql"
sql = open(sqlfile, mode='r', encoding='utf-8-sig').read()
curDest.execute(sql)
Run Code Online (Sandbox Code Playgroud)

看起来效果很好!