我有一個 CSV 檔案,其中我在三列中有資料,我想在檢查資料存在后添加新行,然后想在新行中添加這些資料但收到錯誤list index out of range
這是我的代碼
類別
name
apple
banana
potatoes
onion
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()
注意:資料已添加到現有 CSV 檔案中,但 CSV 檔案在每個回圈之間用空行寫入。
uj5u.com熱心網友回復:
原始解決方案的主要問題是處理檔案。外部for回圈不會停止,因為內部 for 回圈正在將行附加到作業檔案中。
在這里,我使用了一個簡單的串列來存盤需要復制的內容。如果檔案太大,另一種選擇是使用第二個 CSV 檔案作為緩沖區,然后在最后將其復制回來。
此外,在進行查找時考慮使用集合,并了解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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/481843.html
上一篇:使用.loc對資料進行分類并使用python將資料框迭代到CSV檔案
下一篇:如果前一個元素是x,則回傳它
