python - 如何在 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 看起来像:
我得到的错误是:
如果仔细查看我的 csv 行,例如:1007740,Hyderabad,"Hyderabad,Telangana,India",9061642.0,IN,City,Active
. 在这里,Canonical_Name
有“,”分隔的字符串导致错误,并假设 CSV 中的列多于表。如何解决这个问题?注意:我假设错误只是由于这个。
CSV 链接
解决方案
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 │
└─────────────┴───────────┴───────────────────────────┴────────────┴──────────────┴─────────────┴────────┘
推荐阅读
- python - 如果我需要在 Pyomo 中使用变量进行条件约束,我应该设置什么类型的优化?
- python - 用之前的非零值替换零
- php - 警告:升级到 PHP 7.2 时遇到的非数字值
- python-2.7 - 使用上下文菜单调用 python 脚本
- python - 用列 max 填充列中的 NaN
- typescript - 对象变量未在方法内更新
- python - 列表自动更改而无需参考
- javascript - ReactJS - 在状态繁重的系统中提升状态
- javascript - 类型错误:无法使用 find() 僧侣读取未定义的属性“then”
- python - 从日志文件中提取特定单词(不是关键字)