字符串格式:迭代csv文件中的行值

时间:2018-04-08 20:45:24

标签: python mysql sql string python-3.x

我有一个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))

1 个答案:

答案 0 :(得分:1)

我不完全确定您要尝试做什么,但要解析csv 文件并使用csv值生成mysql个查询,您可以使用方法:

import csv
csv_path = "C:/Users/HP/PycharmProjects/book_crawler/books/items.csv"
with open(csv_path) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    # skip the first line
    next(readCSV) 
    for row in readCSV:
        # skip blank lines
        if row: 
            # assign variables
            rating = row[0]; product_type = row[1]; upc = row[2]; title = row[3]
            # surround table and fields with  back-tick ` and values with single quote '
            print ("INSERT IGNORE INTO `books_table` (`rating`, `product_type`, `upc`, `title`) VALUES('{}', '{}', '{}', '{}')".format(rating, product_type, upc, title))

<强>输出:

INSERT IGNORE INTO `books_table` (`rating`, `product_type`, `upc`, `title`) VALUES('Three', 'Books', 'a897fe39b1053632', 'A Light in the Attic')
INSERT IGNORE INTO `books_table` (`rating`, `product_type`, `upc`, `title`) VALUES('One', 'Books', '6957f44c3847a760', 'Soumission')