Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

withopen('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)

Solution 2:

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)

Post a Comment for "Writing To Csv With For Loops"