How to write to a CSV file using Python

CSV files are comma separated values and in literally stands for comma separated values. It is a commonly used data format and used by spreadsheets. Python has a csv module in it’s standard library that has classes and methods to perform read/write operations on CSV files. This is the basic stuff: You can change delimiter, newline, write a dictionary, write an iterable using writerows and more.

CSV File in Libre Office

CSV Module in Python

There is a CSV module in python that has functions & classes available to help write and read CSVs, some of them are:

  1. csv.reader function
  2. csv.writer function
  3. csv.DictReader class
  4. csv.Dictwriter class

File Read/Write Modes in Python

Whenever we read from or write to a file in Python, we need to open it first. After completing the required tasks, we need to be close the file so that resources that are tied with the file are freed

  1. r for reading.
  2. r+ opens for reading and writing (cannot truncate a file)
  3. w for writing.
  4. w+ for writing and reading (can truncate a file)
  5. rb for reading a binary file. The file pointer is placed at the beginning of the file.
  6. rb+ reading or writing a binary file.
  7. wb+ writing a binary file.
  8. a+ opens for appending.

Create file and Write to CSV file

First of all you need to create a file and you simply call a function called “open” and specify that you want to write to it. If the file doesn’t exist Python will create it for you.
Here’s code example:

import csv
with open('python.csv', 'w') as csvfile:
    filewriter = csv.writer(csvfile)
    filewriter.writerow(['Name', 'Address'])
    filewriter.writerow(['Arun', 'Delhi'])
    filewriter.writerow(['Vishal', 'New York'])
    filewriter.writerow(['Paul', 'Tokyo'])

Read CSV File

CSV File

To read CSV file or any file for that matter of fact, simply use the open function. Here’s an example

import csv
# create list holders for our data.
names = []
address = []
# open file
with open('python.csv', 'r') as f:
    reader = csv.reader(f)
    # read file row by row
    for row in reader:
        names.append(row[0])
        address.append(row[1])
# Print data
print names
print address

In this tutorial we have covered most of what is required to successfully handle CSV file using the different functions and classes provided by Python. There’s a lot more but CSV files have been widely used in various ares as they are easy to read and manage plus their small size makes them relatively fast to process and transfer. If you are just getting started in Python in Windows, you’ll need PIP for majority of tasks, there are some more python tutorials that can help you in Video Format that you can find here:
Installing PIP in Windows

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

Sharing is caring!

Leave a Comment

Your email address will not be published.