nikki_c
nikki_c

Reputation: 117

Writing to csv with for loops

I am trying to write a new row for each item in list_people with the name and age of the person. If there are 3 people in the list, my CSV should have 3 rows and 2 columns as shown below:

Joann  15
Maria  13
Peter  19

My CSV gives me 1 row and 6 columns as shown below:

Joann 15 Maria 13 Peter 19

Here is the code I am using.

row_lines=[] 

for i in list_people:

    info = inspect.getmembers(i)

    name = info[1]
    row_lines.append(name)
    age = info[2]
    row_lines.append(age)

with open('test.csv', 'w') as csvFile:
    writer=csv.writer(csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(row_lines)

What do I need to change so that it writes to a new row for each iteration of my loop (for each person in the list_people)?

Upvotes: 4

Views: 3757

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

open your csv file once, and write one line per iteration, and no need for so many variables:

with open('test.csv', 'w') as csvFile:
   writer=csv.writer(csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')

   for i in list_people:
       info = inspect.getmembers(i)
       writer.writerow(info[1:3])

or completely replace the for loop by writerows using a generator comprehension, that will be even faster:

writer.writerows(inspect.getmembers(i)[1:3] for i in list_people)

Upvotes: 3

Moses Koledoye
Moses Koledoye

Reputation: 78546

Append each pair of name and age as a list, and then use the writerows method of the csv.writer:

for i in list_people:
    info = inspect.getmembers(i)
    row_lines.append(info[1:3]) # slice [1:3] returns a list of items 1 and 2

with open('test.csv', 'w') as csvFile:
    writer = csv.writer(csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerows(row_lines)

Upvotes: 0

Related Questions