Python csv阅读器表现得很奇怪

时间:2010-05-21 21:15:50

标签: python csv

如果我运行了错误的代码,那就没关系了:

csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
for row1 in csvReader1:
    print row1[0]
    print row1[8]
    category_sku = str(row[8])
    if category_sku == sku:
        classifications["Craft"] = row[0]
        classifications["Theme"] = row[1]

我明白了:

    Knitting
    391
    Traceback (most recent call last):
      File "upload_all_inventory_ebay.py", line 403, in <module>
        inventory_item_list = get_item_list(product)
      File "upload_all_inventory_ebay.py", line 294, in get_item_list
        category_sku = str(row[8])
    NameError: global name 'row' is not defined

Knitting和391完全正确,当然我需要将row [8]称为row1 [8] ... k所以我这样做:

    csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
    for row1 in csvReader1:
        print row1[0]
        print row1[8]
        category_sku = str(row1[8])
        if category_sku == sku:
            classifications["Craft"] = row1[0]
            classifications["Theme"] = row1[1]

我明白了:

...........
Crochet
107452
Knitting
107454
Knitting
107455
Knitting
107456
Knitting
107457
Crochet
108200
Crochet
108201
Crochet
108205
Crochet
108213
Crochet
108214
Crochet
108217

108432
Quilt
108451

108482

108488
Scrapbooking
108711
Knitting
122363
Needlework

Beading

Crafts & Decorating

Crochet

Crochet

Crochet

Traceback (most recent call last):
  File "upload_all_inventory_ebay.py", line 403, in <module>
    inventory_item_list = get_item_list(product)
  File "upload_all_inventory_ebay.py", line 292, in get_item_list
    print row1[0]
IndexError: list index out of range

在你看到的输出中,第0列和第1列中的所有内容都是!!!!!!!!!!为什么?如果不是之前,为什么row1 [0]超出范围。星期五!

1 个答案:

答案 0 :(得分:2)

输出包含每行的结果,因为您要为每一行打印第1列和第9列。

row1[0]超出了任何行的范围,因为文件的特定行上没有任何项目。如果row1没有要访问的项目,则无法访问row1中的第一项。检查每个循环上的row1以查看其中是否包含任何内容。