我正在尝试使用Python将CSV数据导入postgreSQL。我尝试在Stack Overflow上搜索此问题,但无法找到适合我情况的任何结果。我的CSV文件中有空列,当我运行代码时,它会为没有信息的空白列抛出错误。我希望能够告诉Python忽略空白列并继续下一列。并非所有列都包含数据,因此我希望得到您的帮助,以实现一个解决方案,我可以在脚本中为没有数据的列编辑该解决方案。我是编程新手所以请原谅我的愚蠢。
import psycopg2
import csv
csv_data = csv.reader(file('SampleData1.csv'))
database = psycopg2.connect (database = "**", user="**", password="***", host="**", port="**")
cursor = database.cursor()
delete = """Drop table if exists "Real".SampleDataOne"""
print (delete)
mydata = cursor.execute(delete)
cursor.execute("""Create Table "Real".SampleDataOne
(Username varchar(55),
TimeStamp timestamp,
Week date,
Actual_Sale_Date date,
Estimated_Closing_Date date,
Last_Name_First_Name varchar(55),
Ages varchar(55)
);""")
print "Table created successfully"
next(csv_data)
for row in csv_data:
cursor.execute("""Insert into "Real".SampleDataOne(Username,TimeStamp, Week, Actual_Sale_Date, Estimated_Closing_Date, \
Last_Name_First_Name, Ages)"""\
"""VALUES (%s,%s,%s,%s,%s,%s,%s)""",
row)
cursor.close()
database.commit()
database.close()
print "CSV imported"
错误如下:在' False'之后的列旁边有一个点(^)。
Drop table if exists "Real".SampleDataOne
Table created successfully
Traceback (most recent call last):
File "C:/Users/Desktop/Programming/SampleData1Python.py", line 61, in <module>
row)
DataError: invalid input syntax for type date: ""
LINE 1: ...****@jcp.com','****@comcast.net','No','FALSE','','','')
答案 0 :(得分:1)
http://initd.org/psycopg/docs/cursor.html#cursor.copy_from
f = open('SampleData1.csv')
cursor.copy_from(f, '"Real".sampledataone', sep=',', null='')
如果您提供简单的csv数据,而且数据中没有引号或逗号,则应该可以正常工作。