我是靠谱客的博主 俭朴缘分,这篇文章主要介绍python批量读取csv并入库pg,使用Python将CSV数据导入PostgreSQL,现在分享给大家,希望可以做个参考。

I am trying to import CSV data into postgreSQL using Python. I tried to search on Stack Overflow for this issue but couldn't find anything fruition for my situation. I have empty columns in my CSV file, when I run the code it throws out an error for the blank column for which there's no information. I want to be able to tell Python to ignore the blank column and continue to the next column. Not all of the columns have data in them so I want your kind assistance to implement a solution which I can have edited in the script for the columns which have no data in them. I am new to Programming so please pardon my stupidity.

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"

The error is as follows: It has a point upwards (^) next to the column after the '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

row)

DataError: invalid input syntax for type date: ""

LINE 1: ...****@jcp.com','****@comcast.net','No','FALSE','','','')

解决方案f = open('SampleData1.csv')

cursor.copy_from(f, '"Real".sampledataone', sep=',', null='')

Should work provided you have simple csv data without quoting or commas in the data.

最后

以上就是俭朴缘分最近收集整理的关于python批量读取csv并入库pg,使用Python将CSV数据导入PostgreSQL的全部内容,更多相关python批量读取csv并入库pg内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部