首页 > 解决方案 > 如何在 python 的特定场景中忽略 csv 分隔符?

问题描述

我正在尝试使用 CSV 文件在数据库中插入数据。

import psycopg2 #import the postgres library
#connect to the database
conn = psycopg2.connect(host='1.11.11.111',
                   dbname='postgres',
                   user='postgres',
                   password='myPassword',
                   port='1234')  
#create a cursor object 
#cursor object is used to interact with the database
cur = conn.cursor()
#open the csv file using python standard file I/O
#copy file into the table just created 
with open("C:/Users/Harshal/Desktop/tar.csv", 'r') as f:
next(f) 
cur.copy_from(f, 'geotargets_india',sep=',')
conn.commit()
conn.close()
f.close()

我的表如下:

create table public.geotargets_india(
Criteria_ID integer not null,
Name character varying(50) COLLATE pg_catalog."default" NOT NULL,
Canonical_Name character varying(100) COLLATE pg_catalog."default" NOT NULL,
Parent_ID NUMERIC(10,2),
Country_Code character varying(10) COLLATE pg_catalog."default" NOT NULL,
Target_Type character varying(50) COLLATE pg_catalog."default" NOT NULL,
Status character varying(50) COLLATE pg_catalog."default" NOT NULL
)

我的 CSV 看起来像:

CSVIMG

我得到的错误是: 呃 如果仔细查看我的 csv 行,例如:1007740,Hyderabad,"Hyderabad,Telangana,India",9061642.0,IN,City,Active . 在这里,Canonical_Name有“,”分隔的字符串导致错误,并假设 CSV 中的列多于表。如何解决这个问题?注意:我假设错误只是由于这个。 CSV 链接

标签: pythonpostgresqlcsvpsycopg2

解决方案


foo.csv:

It is header which will be ignored------------------------------------
1007740,Hyderabad,"Hyderabad,Telangana,India",9061642.0,IN,City,Active

Python:

import psycopg2
conn = psycopg2.connect('')
cur = conn.cursor()
f = open('foo.csv', 'r')
cur.copy_expert("""copy geotargets_india from stdin with (format csv, header, delimiter ',', quote '"')""", f)
conn.commit()

psql:

table geotargets_india;
┌─────────────┬───────────┬───────────────────────────┬────────────┬──────────────┬─────────────┬────────┐
│ criteria_id │   name    │      canonical_name       │ parent_id  │ country_code │ target_type │ status │
├─────────────┼───────────┼───────────────────────────┼────────────┼──────────────┼─────────────┼────────┤
│     1007740 │ Hyderabad │ Hyderabad,Telangana,India │ 9061642.00 │ IN           │ City        │ Active │
└─────────────┴───────────┴───────────────────────────┴────────────┴──────────────┴─────────────┴────────┘

推荐阅读