【发布时间】:2019-03-04 16:04:01
【问题描述】:
我正在尝试使用命令复制和 Python psycopg2 库上传 CSV 文件。我知道错误源于尝试将 char 值插入双精度列,但我在创建我的 csv 文件时将空值指定为 "NULL",并且在 Postgres 复制命令中我还将空值指定为 "NULL",所以我'不知道为什么它在上传时没有转换这些值。
创建 csv 文件:
with file_path.open(mode='w', newline='') as outfile:
csv_writer = csv.writer(outfile, delimiter=delimiter, quoting=csv.QUOTE_NONNUMERIC)
if include_headers:
csv_writer.writerow(col[0] for col in self.cursor.description)
for row in self.cursor:
csv_writer.writerow(['NULL' if value is None else value for value in row])
将文件上传到 postgres:
sql = """COPY {table} FROM STDIN WITH (DELIMITER '{sep}', NULL 'NULL', FORMAT CSV, HEADER True);""".format(table=table, sep=sep)
with open(file) as f:
self.cursor.copy_expert(sql=sql, file=f, size=size)
self.commit()
错误:
psycopg2.DataError: invalid input syntax for type double precision:
"NULL" CONTEXT: COPY test_table, line 25, column Lat:
"NULL"
【问题讨论】:
标签: python-3.x postgresql csv psycopg2