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

How to read a SQL file with python with proper character encoding?

基于一些示例 (here, here) 我可以使用 psycopg2 读取并希望 运行 来自 python 的 SQL 文件(该文件有 200 行,尽管 运行 很快,但我不想在 python 文件中维护它。

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

sql = open("sql/sm_bounds_current.sql", "r").read()

curDest.execute(sql)

但是,当我运行脚本时,抛出以下错误:

Error: syntax error at or near "drop"
LINE 1: drop table dpsdata.sm_boundaries_current_dev;

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

发现 this post 处理编码和字节顺序标记,这是我的问题所在。

解决方案是从 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)

看起来效果不错!