How to Write to a CSV File in Python


In this article, we show how to write to a comma-separated values (CSV) file in Python.

A comma-separated values file is a file in which commas in between data on the same line represents values for individual columns.

There are 2 ways about going about writing CSV files.

The first approach is you get open up a plain text editor such as notepad and write data separated by commas in between on the same line. Each data in between a comma represents data for a specific column. Each new line represents a new row. You can then take this plain text and have it imported into a CSV file.

The other approach is to write the data directly to a CSV file, which can be done through Python.

Python has a built-in CSV module (already downloaded with the package, so no need to install) that has built-in functions that can write data to a CSV file.

In this article, we show how to write to a CSV file, which can be a Microsoft Excel spreadsheet (probably the most popular one).

So, let's now go over how to do this.

So, the first thing is you have to import the csv module. This is the module that contains many of the functions we use in this code.

Next, we create the CSV data that we want to write to the CSV file.

So, let's just say that we have a CSV file that is composed of students. The file is "Students.csv". It has 2 columns, the student's name and the student's birth year.

Next, in our script, we create a variable named studentsdata. We set the this variable equal to the student's name and the birth year. We have 3 data entries, representing 3 students.

Next, we open the "Students.csv" file with the "w" (write) mode. We open this CSV file as the name, file.

We create the writedata variable. We set this variable equal to csv.writer(file). The next actually writes each of the rows to the CSV file.

And this is all that is needed to write data (rows and columns) to a CSV file with Python.

To see this actual created file, click here: Students.csv.

In this example, we wrote in 3 students' data (3 rows) that each contained two pieces of data (2 columns). However, you could easily create any amount of rows or columns that you desire.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...