gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:09:08 30 4
gpt4 key购买 nike

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

请帮忙......提前谢谢......

最佳答案

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)

但这并不能解决您的问题,因为该文件中存在没有逗号的行,您必须先解决这个问题。

关于python - 列表索引超出范围错误: python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13797829/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com