IndexError:元组索引超出范围python postgresql

时间:2017-08-04 07:19:03

标签: python postgresql csv

import psycopg2
import csv
#import operator
import pandas as pd
database = psycopg2.connect (database = "mydw", user="postgres",                         
password="1234", host="localhost", port="5432")
cursor = database.cursor()
a = pd.read_csv("test.csv")
b = pd.read_csv("test2.csv")
print ("Read file")
c = pd.concat([a, b], join='outer')
c.to_csv("sorted_data.csv", index=False)
mydata = cursor.execute(delete)
cursor.execute("""Create Table Real.region
        (Country varchar(55),
        Capital varchar(55),
        State varchar(55),
        City varchar(55),
        Zip varchar(55)
         );""")

for row in c:
   cursor.execute("""INSERT INTO Real.region (Country, Capital, State,         
    City, Zip)"""\
        """VALUES (%s,%s,%s,%s,%s)""",(row,))            
cursor.close()
database.commit()
database.close()

打印(“导入CSV数据”)

我正在尝试合并2个CSV文件并将结果文件放入 数据库。但我正面临着错误------

  

文件“C:/Users/Administrator/join-col.py”,第42行,在中       msgstr“”“VALUES(%s,%s,%s,%s,%s)”“”,(行,))
  IndexError:元组索引超出范围

请帮忙

1 个答案:

答案 0 :(得分:0)

如果这个

a = pd.read_csv("test.csv")
b = pd.read_csv("test2.csv")
print ("Read file")
c = pd.concat([a, b], join='outer')

在c中放置一个元组列表(你可以通过打印验证它),那么你应该只需要改变它

cursor.execute("""INSERT INTO Real.region (Country, Capital, State,         
City, Zip)"""\
    """VALUES (%s,%s,%s,%s,%s)""",(row,))  

到这个

cursor.execute("""INSERT INTO Real.region (Country, Capital, State,         
City, Zip)"""\
    """VALUES (%s,%s,%s,%s,%s)""",row)   

问题是row已经是一个元组。通过执行(row,),您创建的郁金香只有一个元素,而row本身就是IndexError。 这也是您获得public static void dosomething(File file) { try { BufferedReader in = new BufferedReader(new FileReader(file)); String str; while ((str = in.readLine()) != null) { globalList.add(str); String subString = str.substring(str.indexOf(";") + 1, str.length()); for(Iterator<String> iter = globalList.iterator(); iter.hasNext();) { String elem = (String) iter.next(); if(elem.contains(subString)) iter.remove(); } } } in.close(); } catch (IOException e) { System.out.println(e); } }

的原因