简体   繁体   English

在 CSV 文件中附加数据时列表索引超出范围

[英]list index out of range when appending data in CSV file

I have a CSV file in which I have data in three columns and I want to add new rows after checking the data exists then want to add these data in new rows but getting the error list index out of range我有一个 CSV 文件,其中我在三列中有数据,我想在检查数据存在后添加新行,然后想在新行中添加这些数据,但错误list index out of range

this is my code这是我的代码

Categories类别

name
apple
banana
potatoes
onion

CSV data CSV 数据

titles,summaries,terms
apple,,Apple (Fruit)
banana,,Banana (Fruit)
potatoes,,Potato (Vegitable)
onion,,Onion (Vegitable)    
categories = db.table('categories').get()

csv_data = csv.reader(open('categories.csv', "r"))

csv_matched_strings = []
for row in csv_data:
    for category in categories:
        if category.name in row[0]:
            print(row[0] + ': ' + row[2])
            csv_matched_strings.append(category.name)
            List = [row[0],'',row[2]]
            with open('categories.csv', 'a+') as f_object:
                writer_object = writer(f_object)
                writer_object.writerow(List)
                f_object.close()

Note: Data is added in the existing CSV file but CSV file writing with a blank line between every loop.注意:数据已添加到现有 CSV 文件中,但 CSV 文件在每个循环之间用空行写入。

The main issue with the original solution was handling the file.原始解决方案的主要问题是处理文件。 The outer for loop wouldn't stop, since the inner for loop was appending line to the working file.外部for循环不会停止,因为内部 for 循环正在将行附加到工作文件。

Here, I used a simple list to store what needs to be duplicated.在这里,我使用了一个简单的列表来存储需要复制的内容。 If the file is too large, another option would be to use a second CSV file as a buffer and then copy it back at the end.如果文件太大,另一种选择是使用第二个 CSV 文件作为缓冲区,然后在最后将其复制回来。

Also, consider using sets when doing look-ups and maybe learn about how the in operator works here is a post you might find helpful .此外,在进行查找时考虑使用集合,并了解in运算符的工作原理,这是一篇您可能会觉得有帮助的帖子

import csv
from csv import writer

# Since OP hasn't provided the class, consider this a substitute
categories = [
    {'name': 'apple'},
    {'name': 'banana'},
    {'name': 'potatoes'},
    {'name': 'onion'},
]

# set of category names created using a set comprehension
cat = {c['name'] for c in categories}

found_rows = []
csv_matched_strings = []

with open('categories.csv', "r") as f:
    csv_data = csv.reader(f)

    for row in csv_data:
        if row[0] in cat:
            # First value is found in categories
            print(row[0] + ': ' + row[2])
            found_rows.append([row[0], '', row[2]])
            # I left it here since it was there in the original code
            csv_matched_strings.append(row[0])

# categories.csv is now closed.
# We open it again in append mode and proceed to append the duplicates
with open('categories.csv', 'a+') as f:
    writer_object = writer(f)
    for row in found_rows:
        writer_object.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM