【问题标题】:String Formatting: Iterate the row values from a csv file字符串格式:迭代 csv 文件中的行值
【发布时间】: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


【解决方案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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2017-08-28
    • 2020-12-25
    • 2019-05-06
    相关资源
    最近更新 更多