列表索引超出范围错误:python

时间:2012-12-10 09:05:38

标签: python mysql sql

import MySQLdb
import pyodbc


typesFile = open('servinfo.txt', 'r').readlines()
dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)   


conn = pyodbc.connect('DRIVER={FreeTDS}; SERVER=prsoft; DATABASE=blueseas; UID=sa;    PWD=tiger')
msCursor = conn.cursor()


db = MySQLdb.connect(passwd="pr", db="tenable")
myCursor = db.cursor()

msCursor.execute("SELECT * FROM airlinemaster WHERE type='U'") 
dbTables = msCursor.fetchall()
noLength = [56, 58, 61] 

for tbl in dbTables:
msCursor.execute("SELECT * FROM airlinemaster WHERE airline = air india('%s')" % tbl[0]) #syscolumns: see sysobjects above.
columns = msCursor.fetchall()
attr = ""
for col in columns:
colType = dataTypes[str(col.xtype)] 


if col.xtype == 60:
    colType = "float"
    attr += col.name +" "+ colType + "(" + str(col.length) + "),"
elif col.xtype in noLength:
    attr += col.name +" "+ colType + ","
else:
    attr += col.name +" "+ colType + "(" + str(col.length) + "),"

attr = attr[:-1]
myCursor.execute("CREATE TABLE " + tbl[0] + " (" + attr + ");") #create the new table and all columns
msCursor.execute("select * from %s" % tbl[0])
tblData = msCursor.fetchall()

#populate the new MySQL table with the data from MSSQL
for row in tblData:
fieldList = ""
for field in row:
    if field == None: 
    fieldList += "NULL,"
    else:
    field = MySQLdb.escape_string(str(field))
    fieldList += "'"+ field + "',"

fieldList = fieldList[:-1]
myCursor.execute("INSERT INTO " + tbl[0] + " VALUES (" + fieldList + ")" )

我在很多方面尝试了上面的代码来导入数据..但仍然继续得到错误作为列表索引超出范围..不知道我哪里出错了...我该如何解决这个?

 Traceback (most recent call last):
 File "C:\Python27\programs new\codes.py", line 10, in <module>
 dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)
 File "C:\Python27\programs new\codes.py", line 10, in <genexpr>
 dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)
 IndexError: list index out of range

请帮助.... thnx提前..

1 个答案:

答案 0 :(得分:1)

row中至少有一个typesFile没有,逗号:

>>> 'line without a comma'.split(',')
['line without a comma']
>>> 'line without a comma'.split(',')[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

如果servinfo.txt应该是包含两列的逗号分隔文件,为什么不使用csv模块来读取它呢?

import csv
csvreader = csv.reader(open('servinfo.txt', 'rb'))
dataTypes = dict(csvreader)

这不能解决你的问题,因为在该文件中有一行没有逗号,你必须先修复它。