Write to a csv file in loop in Python

In this article, we will discuss how to write to a csv file in a for loop in Python.

Table Of Contents

Introduction

We can iterate over a range of numbers in a for loop, and add lines to the csv file during iteration. For this example, we will iterate over a range from 0 to 9, and in each iteration we will create a list of random numbers. Then using the csv writer’s writerow() function, we will append that list as a row in the csv file.

Important Point: We are going to use the csv module.

Detailed steps

  • Open file in write mode, and it will give a file object.
  • Pass the file object to the writer() function of csv module. It will give a csv writer object.
  • Add a list of strings as header of the csv file by calling the writerow() function of csv writer object.
  • Iterate over a range from 0 to 9. In each iteration,
    • Create a list of random numbers.
    • Append that list to csv file as row using the writerow() function of csv writer object.
  • In the end, we will have a csv file with 10 rows of random numbers and a header row.

Let’s see a complete example,

Code Example

import csv
import random

# Open the csv file for writing
with open('numbers.csv', 'w') as fileObj:
    # Creater a CSV writer object
    writerObj = csv.writer(fileObj)
    # Add header row as the list
    writerObj.writerow(['first', 'second', 'third', 'fourth', 'fifth'])
    for i in range(10):
        # Create a list of 5 random numbers between 1 to 100
        listOfNumbers = random.sample(range(1, 100), 5)
        # Append the list as a row to the csv file
        writerObj.writerow(listOfNumbers)

This code create a csv file numbers.csv with ten rows of random numbers and a header row.

Contents of file numbers.csv will be like this,

first,second,third,fourth,fifth
69,12,45,2,58
13,78,62,15,49
38,50,10,84,93
77,26,27,99,84
90,42,16,54,46
16,81,2,91,59
42,62,60,92,34
10,70,31,58,54
72,10,85,84,67
35,8,54,40,77

Summary

We learned how to write to a csv file in a for loop in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top