【发布时间】:2018-04-08 20:45:24
【问题描述】:
我有一个 csv 文件。我想迭代行并生成 sql 字符串。我尝试了 stackoverflow 中的解决方案,但无法修复它。
csv 文件
rating,product_type,upc,title
Three,Books,a897fe39b1053632,A Light in the Attic
One,Books,6957f44c3847a760,Soumission
python 文件以以下代码开头
path = r'C:\Users\HP\PycharmProjects\book_crawler\books\items.csv'
file = open(path, 'rt')
我尝试了不同版本的字符串格式化。我得到的一些错误:
IndexError:元组索引超出范围
for row in file:
print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({},{},{},{})'.format(row))
TypeError:字符串格式化期间并非所有参数都转换
for row in file:
print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % row)
TypeError:字符串格式化期间并非所有参数都转换
for row in file:
print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % (row,))
TypeError:字符串格式化期间并非所有参数都转换
for row in file:
print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % tuple(row))
【问题讨论】:
-
为什么要创建
insert?只需使用load data infile。 -
从
print(row)开始。这将向我们(和您)解释参数的数量哪里出错了。 -
你真的解析了 CSV 文件吗?
-
您可能正在解析 csv 的第一行,使用
next()跳过它,还要确保row在处理之前不为空。将代码分成块并正确调试。 -
这是我的代码的一部分。我正在抓取一些数据来加载 mysql。
标签: python mysql sql string python-3.x