csv “索引错误:通过for循环从列表中注入SQL语句时,字符串索引超出范围

z5btuh9x  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(74)

我尝试用psycopg 2将.csv文件的一列读入数据库。.csv中的列中的数据采用以下形式:<other_col>流派<...>摇滚|流行|金属末日摇滚|...
我首先逐行读取这些值并进行拆分“|“,它们并将所有内容附加到一个列表中,在该列表中,我使用set删除重复项。我的输入文件需要一点格式,并且必须是唯一的,因此我将值转换为列表(set(data))。
当for-looping遍历上述列表以构建应该植入值的SQL语句时,我得到“IndexError:字符串索引超出范围”,我不明白为什么,因为我从列表中读取元素,而不是单个字符串。有人能给予我一个提示吗,我失败的地方?

test = csv_to_dict("artists.csv", "\t")    #this is a predefined function, that just reads csv.dictReader and the csv-file is tab-separated.

genre_list =[]
for row in test:
    genres = (row['genres'])
    genres = (genres.split(sep="|"))    # this is to "clean" and generate list with unique genres
    for p in genres:
        genre_list.append(p.title())
genre_list = list(set(genre_list))
genre_list.sort()

cur = sql_con.cursor()
sql = 'INSERT INTO Genre (GenreName) VALUES(%s);' # here I expect genre from genre_list to be inserted @ %s
for genre in genre_list:
    cur.execute(sql, genre)
sql_con.commit()

测试结果:

Traceback (most recent call last):
  File "/Users/.../IngestData.py", line 76, in <module>
    cur.execute(sql, t)
IndexError: string index out of range
fdx2calv

fdx2calv1#

我得到了同样的错误,因为x=(1)not 创建了一个具有单个值的列表。要创建一个单值列表/元组,你需要在末尾加上逗号:

foo=(1)
print(foo)
Out[7]: 1

bar=(1,)
print(bar)
Out[9]: (1,)

相关问题