bobdaves69
bobdaves69

Reputation: 79

How to append multiple rows to csv file using python

Im trying to append user inputted data to rows , however im having no luck.

Counter is a user defined global variable which i have created elsewhere in the code.

when the data is appended, instead of moving to another line it just rewrites the same line over and over and as a new user of python i have no idea what im doing wrong.

def AppendCsv(): 
    NumberOfNamesToBeAdded()
    with open ('Graph.csv', 'a') as graphFile:
        graphFileWriter=csv.writer(graphFile)
        for x in counter:
             graphFileWriter.writerow([ID, Name,Cost,Date1]) 

Upvotes: 0

Views: 6999

Answers (1)

Bill Bell
Bill Bell

Reputation: 21663

It depends what's in counter, for one thing. With a range in counter, like this:

import csv

counter = range(3)

with open('Graph.csv', 'a', newline='') as graphFile:
    graphFileWriter = csv.writer(graphFile)
    for x in counter:
        graphFileWriter.writerow([1,2,3])

the result is this:

1,2,3
1,2,3
1,2,3

You might also want to insert , newline='' in the open statement.

Upvotes: 1

Related Questions