【问题标题】:Psycopg2 copy_from for csv to postgress用于 csv 到 postgres 的 Psycopg2 copy_from
【发布时间】:2021-04-24 06:19:33
【问题描述】:

我有一个读取到 pandas 的 csv 文件,我应该插入到 postgres 中。该文件在某些​​字段中包含带有反斜杠“字符”的字符串。这会导致问题,因为 copy_from 函数将其读取为转义字符。我如何让它忽略“”并将其保留为字符串。我尝试了许多不同的编码格式,但仍然出现“无法解码字符”错误。问题是我不能替换那个字符,它在字符串中很重要。

def load_into_db(cur, con, file,table_name):
f = open(file, mode="r", encoding='utf-8')
try:
    # print("wrote to csv")
    sqlstr = "COPY {} FROM STDIN DELIMITER '|' CSV".format(table_name)
    cur.copy_from(f, table_name, null="nan", sep="|")
    con.commit()
    f.close() 
except Exception as e:
    print(e)
    print("something went wrong")

导致问题的行示例

name age attribute
name1 23 example/1/test
name2 26 example/2/test

错误:编码“UTF8”的字节序列无效:0xa2

【问题讨论】:

  • 您能否分享导致此问题的 csv 示例行并重现该错误?
  • 抱歉,仍然无法重现——当我使用您的示例为自己创建表和文件时,您的示例没有任何问题。请包含minimal, complete, reproducible example,包括创建表的命令,并附加 csv 文件本身(或 stringio 等价物)——您的示例也是制表符分隔的,仅包含正斜杠字符而不是反斜杠

标签: python pandas postgresql psycopg2


【解决方案1】:
import io
import csv
def df2db(df_a, table_name, engine):
    output = io.StringIO()
    # ignore the index
    # df_a.to_csv(output, sep='\t', index = False, header = False, quoting=csv.QUOTE_NONE)
    df_a.to_csv(output, sep='\t', index = False, header = False, quoting=csv.QUOTE_NONE, escapechar='\\')
    output.getvalue()
    # jump to start of stream
    output.seek(0)
    
    #engine <--- from sqlalchemy import create_engine
    connection = engine.raw_connection() 
    cursor = connection.cursor()
    # null value become ''
    cursor.copy_from(output,table_name,null='')
    connection.commit()
    cursor.close()

使用函数df2dbDataFrame 插入到存在的表中,因为表的cols 和df 的列应该相同。

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:psw@localhost:5432/dbname')
df = pd.read_csv(file)
df2db(df, table_name, engine)

【讨论】:

  • 这完美解决了我的波浪号分隔文件中有人输入“A~B~K\~F~X”的问题,现在我在我的数据库中输入为“K\”不是问题。谢谢!
猜你喜欢
  • 2022-01-08
  • 2022-01-08
  • 1970-01-01
  • 2021-12-19
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多