【发布时间】:2021-07-03 18:11:29
【问题描述】:
我正在尝试将内容添加到我现有的 csv 文件中。这意味着我不想删除任何现有内容,而只想根据列表添加新行。
但是,在最终输出中,我没有看到 csv 中添加了任何新行。该变量还返回空列表值(请参阅代码行上的注释)。
这里我首先询问用户条目的数量。然后是每个条目的值(每列的每一行值)。然后我很简单地将它附加到最终列表中,即 total_number_of_rows 应该如下所示: [[x,x,x][xy,xy,xy].
在最终代码中,我尝试将两个列表中的值写入 CSV 文件,例如最终输出应如下所示:
id, name, color
oldvalue1, oldvalue2, oldvalues3 #assuming this is an already existing row in the csv file
x,x,x
xy,xy,xy
number_of_entries = int(input("how many entries will you need to enter:"))
each_new_row = []
total_number_of_rows = []
for i in range(number_of_entries):
new_id = input("add new new_id")
new_name = input ("add new date")
new_color = input ("add new color")
each_new_row.extend((new_id,new_name,new_color))
print("each_new_row",each_new_row)
total_number_of_rows.append(each_new_row)
print("total number of rows", total_number_of_rows) # this is showing [[1,1,red],[2,2,blue]]
each_new_row.clear()
print("total_number_of_rows", total_number_of_rows) ## this is showing [[],[]]
with open('file.csv', 'a',newline ="") as f:
writer = csv.writer(f)
writer.writerows(total_number_of_rows)
#not seeing any new row added
【问题讨论】:
-
我正在使用 list 方法用值填充 total_number_of_rows。不知何故,这没有通过。即使我在 each_new_row.clear() 之后添加 print("total_number_of_rows", total_number_of_rows) ,即直接在其下方,它也会显示相同的结果
-
# this is showing [[1,1,red],[2,2,blue]]这不是真的,你应该再检查一次。也许你会注意到问题所在。 -
是
each_new_row.clear()引起的问题。如果您注释掉这两个total_number_of_rowsprint statments 正常工作,但是您的列表没有正确分成子列表 -
它可能会显示
[[1,1,red]]或[[2,2,blue], [2,2,blue]],但不会显示[[1,1,red], [2,2,blue]]。 -
@JD2775 正是我试图删除它,你能建议我如何解决这个问题吗?
标签: python loops csv file write