Python CSV Read Write With Examples

In this tutorial we will learn about the python csv module that already exist with the python. In our previous tutorial, we have seen python mysql example.

Python CSV

CSV stands for comma separated values. In this tutorial we will see how to read and write CSV files in python. Python provides a module named csv, using this we can do several operations on the csv files.

Python CSV file

As I said before CSV is a file format. Python CSV module will help to read and write in the csv file.

The following is an example of csv file. The file name is employeeInfo.csv that is taken from an excel sheet containing the information of employee name, department and email address.

employeeInfo.csv

We have to keep this csv file in the same directory from where we want to access this file using python.

Python Read CSV

We can read the contents of csv file as followings with the help of csv.reader() method.

Below image shows the output produced by above python csv read example program.

Python CSV Read Write

So we have read our csv file. What if we want to get the specific columns like only name and email address. Then we have to do as following:

It will output only the name and email address of the employee.

Python CSV Read Write

Python CSV Writer

You can also write in csv file using python csv module. To write in the file you can open the file in write mode or you may open the file in append mode.

Then you have to use python csv.writer() to write in the csv file. The following is a example which writes in a csv file named output.csv.

Now you will see a file named output.csv in the same directory. Open that file, and you will find the values that you have wrote in it.

Python CSV Read Write

To know more about python csv I should recommend you to visit the official website.

By admin

Leave a Reply

%d bloggers like this: