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

2024-04-26 12:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试了不同版本的字符串格式。我得到的一些错误:

索引器:元组索引超出范围

for row in file:
    print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({},{},{},{})'.format(row))

类型错误:并非所有参数都在字符串格式化期间转换

for row in file:
    print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % row)

类型错误:并非所有参数都在字符串格式化期间转换

for row in file:
    print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % (row,))

类型错误:并非所有参数都在字符串格式化期间转换

for row in file:
    print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % tuple(row))

Tags: 字符串infortitletype错误productbooks
1条回答
网友
1楼 · 发布于 2024-04-26 12:07:40

我不完全确定您想做什么,但是要分析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')

相关问题 更多 >