【发布时间】: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
...
我的列 label 和 mids 中有昏迷,这就是为什么我收到以下错误:
BadCopyFileFormat: ERROR: additional data after the last expected column
我应该使用哪个替代方法从这个 csv 文件中复制数据?
ty
【问题讨论】:
-
您可以尝试更改 CSV 中的分隔符,以免与文本中的逗号冲突。如';'。
标签: python postgresql csv psycopg2