开发者

Copy data from csv file

开发者 https://www.devze.com 2023-02-19 19:34 出处:网络
I am trying to follow one copy_from example describe in stackoverflow but i modify little as i need to 开发者_高级运维read data from csv file. Following this example i wrote a small program where the

I am trying to follow one copy_from example describe in stackoverflow but i modify little as i need to 开发者_高级运维read data from csv file. Following this example i wrote a small program where the file is to be readed from file stored in disk and then copy data from that file to created table, My code is :

def importFile():
    path = "C:\myfile.csv"
    curs = conn.cursor()
    curs.execute("Drop table if exists test_copy; ")
    data = StringIO.StringIO()
    data.write(path)
    data.seek(0)
    curs.copy_from(data, 'MyTable')
    print("Data copied")

But i get error,

psycopg2.DataError: invalid input syntax for integer:

Does this mean there is mismatch between csv file and my table? OR is this syntax enough in order to copy csv file? or I need some more code ?? I am new to python, so any help will be appreciated..


Look at your .csv file with a text editor. You want to be sure that

  • the field-separator is a tab character
  • there are no quote-chars
  • there is no header row

If this is true, the following should work:

import psycopg2

def importFromCsv(conn, fname, table):
    with open(fname) as inf:
        conn.cursor().copy_from(inf, table)

def main():
    conn = ??  # set up database connection
    importFromCsv(conn, "c:/myfile.csv", "MyTable")
    print("Data copied")

if __name__=="__main__":
    main()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号