Categories
Python Answers

How to write to a CSV line by line with Python?

Spread the love

Sometimes, we want to write to a CSV line by line with Python.

In this article, we’ll look at how to write to a CSV line by line with Python.

How to write to a CSV line by line with Python?

To write to a CSV line by line with Python, we can use the CSV writer.

For instance, we write

import csv

with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

to call open to open the csv file with write permission and as a binary file.

Then we call csv.writer with the opened csv_file to create a writer object.

We set the delimiter to the delimiter of the row items.

And then we add a for loop that calls writerow to write the line to the csv.

Conclusion

To write to a CSV line by line with Python, we can use the CSV writer.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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