如何在python中的特定场景中忽略csv分隔符?
我正在尝试使用CSV文件在DB中插入数据如何在python中的特定场景中忽略csv分隔符?,python,postgresql,csv,psycopg2,Python,Postgresql,Csv,Psycopg2,我正在尝试使用CSV文件在DB中插入数据 import psycopg2 #import the postgres library #connect to the database conn = psycopg2.connect(host='1.11.11.111', dbname='postgres', user='postgres', password='myPassword',
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看起来像:
我得到的错误是:
如果仔细查看我的csv行,例如:1007740,海得拉巴,“印度泰兰加那海得拉巴”,9061642.0,IN,City,Active
。此处,Canonical_Name
用“,”分隔字符串,该字符串导致错误,并假设CSV中的列多于表中的列。如何解决这个问题?
注意:我假设错误只是由于这个原因。
您可能应该自己在Python中读取并解析CSV文件,然后使用
INSERT
语句将数据加载到数据库中
导入csv
导入psycopg2
conn=psycopg2.connect(
host='1.11.11.111',
dbname='postgres',
user='postgres',
password='myPassword',
端口='1234'
)
cur=连接光标()
打开(“tar.csv”)作为fd:
rdr=csv.DictReader(fd)
当前执行官(“”)
插入geotargets\u india
值(%(标准ID)s、%(名称)s、%(规范名称)s、%(父ID)s、%(国家/地区代码)s、%(目标类型)s、%(状态)s);
""",
rdr
)
当前关闭()
康涅狄格州关闭
对以上几点意见。该类将返回CSV的词典。返回的DictReader对象,
rdr
,是可编辑的,因此可以直接在psycopg2的函数中使用,这可能比自己遍历csv DictReader对象更有效。关于规范名称中的问题,您是对的。我成功地将行1007740,海得拉巴,“海得拉巴”,9061642.0,在,城市,活动
表中导入到您的结构中
不幸的是,copy_from方法不支持csv separator参数。这是文件
因此,您可以使用制表符分隔符重新格式化csv文件,然后使用copy_from
import 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:
reader = csv.reader(f, delimiter=",")
with open("C:/Users/Harshal/Desktop/tar.tsv", 'w') as tsv:
writer = csv.writer(tsv, delimiter='\t')
writer.writerows(reader)
with open("C:/Users/Harshal/Desktop/tar.tsv", 'r') as f:
next(f)
cur.copy_from(f, 'geotargets_india',sep='\t')
conn.commit()
conn.close()
f.close()
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:
在导入之前我必须安装CSV,对吗?我尝试了pip安装csv,但得到的错误是:找不到满足要求的版本csv(从版本:无)错误:找不到csv的匹配发行版。不,
csv
是Python标准库的一部分,因此您不必安装它。查看它的感谢,但仍然得到错误InvalidTextRepresentation:type numeric的无效输入语法:“第3行:值('2356','India','India','IN','Country…
,来自第22行cur.executemany(“看起来像该行中的父ID(第四个值))PysCopg2,一个空字符串(<代码> '/COD> >与数值类型不兼容。如果您希望在这种情况下出现空值,则需要将空字符串转换为<代码> No.< /代码>。“上下文:复制geotargets\u india,第1行,列标准\u id:”在“cur.COPY\u from”(f,“geotargets\u india”,sep='\t'行)“可能你需要我有一个后续问题:我们如何使用数据框而不是拾取保存的文件,而不是将CSV作为文件读取?我正在使用pandas操作原始CSV。@eras'q抱歉,我不是Python/pandas专家,只是从这里和那里获得了一些知识。
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 │
└─────────────┴───────────┴───────────────────────────┴────────────┴──────────────┴─────────────┴────────┘