Python CSV Module: Read and Write CSV Files

The CSV (Comma Separated Values) format is a very popular import and export format used in spreadsheets and databases. Python language contains the csv module which has classes to read and write data in the CSV format. In this article, we will explore how to use csv.reader(), csv.writer(), csv.DictReader(), and csv.DictWriter() methods, each with practical examples.

Let’s suppose that we have the following person.csv file containing the information of 4 persons. We will read this file in different ways.

Alice,29,New York,Engineer,
Bob,35,Los Angeles,Doctor,

1. Reading a CSV File

1.1. Using csv.reader()

The csv.reader() function is used to read data from a CSV file. It takes a file object and returns a reader object that iterates over lines in the given CSV file.

In the following code example, we are opening the person.csv for reading and loading the data with the csv.reader() method.

import csv

# File path of the CSV file
file_path = 'person.csv'

# Reading the data from the CSV file
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
  reader = csv.reader(file)
  for row in reader:

The program output:

['Name', 'Age', 'City', 'Occupation', 'Email']
['Alice', '29', 'New York', 'Engineer', '']
['Bob', '35', 'Los Angeles', 'Doctor', '']
['Charlie', '45', 'Chicago', 'Teacher', '']
['Diana', '32', 'Miami', 'Artist', '']

1.2. Using csv.DictReader()

The csv.DictReader class operates like a regular reader but maps the information read into a dictionary. The keys for the dictionary can be passed in with the fieldnames parameter or inferred from the first row of the CSV file.

The first row represents the keys to the Dictionary and the second row represents the values.

import csv

# File path of the CSV file
file_path = 'person.csv'

# Reading the data from the CSV file as dictionaries
data_dict_read = []
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:

The program output is as follows where each row is represented as a dictionary where the keys are the column headers from the CSV file.

{'Name': 'Alice', 'Age': '29', 'City': 'New York', 'Occupation': 'Engineer', 'Email': ''}
{'Name': 'Bob', 'Age': '35', 'City': 'Los Angeles', 'Occupation': 'Doctor', 'Email': ''}
{'Name': 'Charlie', 'Age': '45', 'City': 'Chicago', 'Occupation': 'Teacher', 'Email': ''}
{'Name': 'Diana', 'Age': '32', 'City': 'Miami', 'Occupation': 'Artist', 'Email': ''}

2. Write a CSV File

2.1. Using csv.writer()

The csv.writer() method returns a writer object responsible for converting the user’s data into delimited strings on the given file-like object.

import csv

# Sample data to be written to the CSV file
data = [
  ['Name', 'Age', 'City', 'Occupation', 'Email'],
  ['Alice', 29, 'New York', 'Engineer', ''],
  ['Bob', 35, 'Los Angeles', 'Doctor', ''],
  ['Charlie', 45, 'Chicago', 'Teacher', ''],
  ['Diana', 32, 'Miami', 'Artist', '']

# File path for the CSV file
file_path = 'person_new.csv'

# Writing the data to the CSV file
with open(file_path, mode='w', newline='', encoding='utf-8') as file:
  writer = csv.writer(file)

This example writes numbers into the person-new.csv file. The writerows() method writes all the rows of data into the specified file. The script produces the following file (person-new.csv):

Alice,29,New York,Engineer,
Bob,35,Los Angeles,Doctor,

2.2. Using csv.DictWriter()

The csv.DictWriter() writes dictionaries to a CSV file. This is useful when your data is in dictionary form and you want to preserve column headers.

In the following example, the fieldnames specifies the order and presence of fields in the CSV output. The writeheader() method writes the header row with field names.

import csv

# Sample data in dictionary format
data_dicts = [
  {'Name': 'Alice', 'Age': 29, 'City': 'New York', 'Occupation': 'Engineer', 'Email': ''},
  {'Name': 'Bob', 'Age': 35, 'City': 'Los Angeles', 'Occupation': 'Doctor', 'Email': ''},
  {'Name': 'Charlie', 'Age': 45, 'City': 'Chicago', 'Occupation': 'Teacher', 'Email': ''},
  {'Name': 'Diana', 'Age': 32, 'City': 'Miami', 'Occupation': 'Artist', 'Email': ''}

# File path for the new CSV file
file_path_dict_writer = 'person_dict_written.csv'

# Writing the data to the new CSV file using DictWriter
with open(file_path_dict_writer, mode='w', newline='', encoding='utf-8') as file:
  fieldnames = ['Name', 'Age', 'City', 'Occupation', 'Email']
  writer = csv.DictWriter(file, fieldnames=fieldnames)

  for row in data_dicts:

3. Customizing Delimiters and Quote Characters

We can customize the delimiter and quote characters in csv.reader() and csv.writer() functions using the delimiter and quotechar arguments.

For example, we have person_data.tsv file which is a tab-separated file and fields are quoted with the | character.

|Name|	|Age|	|City|	|Occupation|	|Email|
|Alice|	|29|	|New York|	|Engineer|	||
|Bob|	|35|	|Los Angeles|	|Doctor|	||
|Charlie|	|45|	|Chicago|	|Teacher|	||
|Diana|	|32|	|Miami|	|Artist|	||

The following code reads the person_data.tsv file and prints the content in console.

import csv

with open('example.tsv', mode='r') as file:
    reader = csv.reader(file, delimiter='\t', quotechar='|')
    for row in reader:

When writing the CSV file, there are four different quoting modes in the Python CSV module:

  • QUOTE_ALL: quotes all fields
  • QUOTE_MINIMAL: quotes only those fields that contain special characters
  • QUOTE_NONNUMERIC: quotes all non-numeric fields
  • QUOTE_NONE: does not quote fields

In the next example, we write three rows to the items2.csv file. All non-numeric fields are quoted.

import csv

f = open('person_data_new.tsv', 'w')

with f:

    writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerows((["coins", 3], ["pens", 2], ["bottles", 7]))

The program creates the following person_data_new.csv file. The item names are quoted, but the quantities expressed in numbers are not quoted.


4. CSV Dialects

Despite the CSV format being a very simple format, there can be many differences, such as different delimiters, new lines, or quoting characters. Therefore, there are different CSV dialects available.

The next code example prints the available dialects and their characteristics.

import csv

names = csv.list_dialects()

for name in names:


    dialect = csv.get_dialect(name)

    print(repr(dialect.delimiter), end=" ")
    print(dialect.doublequote, end=" ")
    print(dialect.escapechar, end=" ")
    print(repr(dialect.lineterminator), end=" ")
    print(dialect.quotechar, end=" ")
    print(dialect.quoting, end=" ")
    print(dialect.skipinitialspace, end=" ")

The csv.list_dialects() returns the list of dialect names and the csv.get_dialect() method returns the dialect associated with the dialect name.

',' True None '\r\n' " 0 False False
'\t' True None '\r\n' " 0 False False
',' True None '\n' " 1 False False

The program prints this output. There are three built-in dialects: excel, excel-tab and unix.

5. Using a Custom CSV Dialect

In the last example of this tutorial, we will create a custom dialect. A custom dialect is created with the csv.register_dialect() method.

import csv

csv.register_dialect("hashes", delimiter="#")

f = open('items3.csv', 'w')

with f:

    writer = csv.writer(f, dialect="hashes")
    writer.writerow(("pencils", 2))
    writer.writerow(("plates", 1))
    writer.writerow(("books", 4))

The program uses a (#) character as a delimiter. The dialect is specified with the dialect option in the csv.writer() method. The program produces the following file (items3.csv):


6. Conclusion

In this tutorial, we have explored the Python csv module and gone through some examples of reading and writing CSV files in Python using the methods csv.reader(), csv.writer(), csv.DictReader(), and csv.DictWriter().

Remember to handle different file encodings and delimiters as per your data requirements.

Happy Learning !!

Source Code on Github


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode