简体   繁体   English

从csv文件复制数据

[英]Copy data from csv file

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. 我试图在stackoverflow中跟随一个copy_from示例描述但我修改很少因为我需要从csv文件中读取数据。 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: psycopg2.DataError:整数的输入语法无效:

Does this mean there is mismatch between csv file and my table? 这是否意味着csv文件和我的表之间存在不匹配? OR is this syntax enough in order to copy csv file? 或者这个语法是否足以复制csv文件? or I need some more code ?? 或者我还需要更多代码? I am new to python, so any help will be appreciated.. 我是python的新手,所以任何帮助都将受到赞赏..

Look at your .csv file with a text editor. 使用文本编辑器查看.csv文件。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM