【问题标题】:Other way than splitting with coma to store in a database?除了用逗号拆分以存储在数据库中之外的其他方式?
【发布时间】:2021-06-10 12:40:45
【问题描述】:

我开始使用 postgresql 创建数据库,当我想将数据从 csv 文件复制到数据库时遇到问题

这是我的代码:

connexion = psycopg2.connect(dbname= "db_test" , user = "postgres", password ="passepasse" )
connexion.autocommit = True
cursor = connexion.cursor()
cursor.execute("""CREATE TABLE vocabulary(
    fname integer PRIMARY KEY,
    label text,
    mids text
    )""")

with open (r'C:\mypathtocsvfile.csv', 'r') as f:
    next(f) # skip the header row
    cursor.copy_from(f, 'vocabulary', sep=',')
    
connexion.commit()

我要求分配 4 列来存储我的 csv 数据,问题是我的 csv 中的数据是这样存储的:

fname,labels,mids,split
64760,"Electric_guitar,Guitar,Plucked_string_instrument,Musical_instrument,Music","/m/02sgy,/m/0342h,/m/0fx80y,/m/04szw,/m/04rlf",train
16399,"Electric_guitar,Guitar,Plucked_string_instrument,Musical_instrument,Music","/m/02sgy,/m/0342h,/m/0fx80y,/m/04szw,/m/04rlf",train
...

我的列 labelmids 中有昏迷,这就是为什么我收到以下错误:

BadCopyFileFormat: ERROR: additional data after the last expected column

我应该使用哪个替代方法从这个 csv 文件中复制数据?

ty

【问题讨论】:

  • 您可以尝试更改 CSV 中的分隔符,以免与文本中的逗号冲突。如';'。

标签: python postgresql csv psycopg2


【解决方案1】:

如果文件很小,那么最简单的方法是在 LibreOffice 中打开文件并使用新的分隔符保存文件。我通常使用 ^.如果文件很大,写一个脚本,分别在^"和"^"上替换,"和","。

【讨论】:

  • 是的,这是一个大文件,谢谢你的提示,我会试试这个
【解决方案2】:

COPY 支持 csv 作为一种格式,它已经可以满足您的需求。但是要通过 psycopg2 访问它,我认为您需要使用 copy_expert 而不是 copy_from。

cursor.copy_expert('copy vocabulary from stdin with csv', f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2017-03-03
    • 2011-10-06
    • 2012-01-24
    • 2018-06-15
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多