I am trying to add content to my existing csv file. meaning I would not like to remove any existing content but just like to add new lines based on list of lists.
However, in the final output I don't see any new row being added in the csv. Also the variable is returning empty list values (please see the comment on the code line).
Here i am asking the user first the number of entries. then value for each entry (each row value for each column). Then I am simple appending it to a final list i.e total_number_of_rows which should look like: [[x,x,x][xy,xy,xy].
In the final code I am trying to write the values from the two lists to the CSV file for example the final output should look like:
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
# this is showing [[1,1,red],[2,2,blue]]that's not true, you should check that again. Maybe you will notice what the problem is then.each_new_row.clear()that's causing the issue. If you comment that out bothtotal_number_of_rowsprint statments work correctly, but then your lists aren't separated correctly into sublists[[1,1,red]]or[[2,2,blue], [2,2,blue]], but not[[1,1,red], [2,2,blue]].