How to Write CSV File in Python

In Python, the creation of CSV files can be accomplished using the csv module. CSV, which stands for Comma-Separated Values, serves as a straightforward file format designed for the storage of tabular data, including information sourced from spreadsheets or databases, in a plain text format.

Every line of information in a CSV file corresponds to a distinct entry in a plain text document, with separate data items (or cells) in each line generally divided by commas. Although commas serve as the default separator, alternative characters such as tabs or semicolons may also be utilized, influenced by local conventions or the specifications of a specific application.

There are multiple approaches to generating CSV files in Python. Several of these methods are detailed below:

1) Write CSV Files Using csv.DictWriter in Python

Utilizing the python csv.DictWriter, every row will be depicted as a dictionary, where the header is represented as keys corresponding to the individual dictionaries that comprise the dataset.

Syntax:

It has the following syntax:

Example

csv.DictWriter(file, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwargs)

Parameters:

  • file: Represents the CSV file where data is intended to be stored in the form of a table in write mode.
  • fieldnames: This set of arguments is meant to contain a collection of strings that enumerate to form keys serving as headers in the foremost row of the output table.
  • restval (optional): Specifies default values for keys that do not correspond to an existing key in the dictionary.
  • extrasaction (optional): Specifies the handling of keys that are not expected in the arguments.
  • dialect (optional): Responsible for setting the manner that will be used for certain parameters pertaining to the data file, for instance, quotation marks, delimiters, as well as str.
  • Python Example to Write CSV Files using the csv.DictWriter Method

Let us consider an illustration to show how to create a CSV file utilizing the csv.DictWriter method in Python.

Example

import csv

# List of dictionaries representing rows

data = [

    {'Name': 'John', 'Age': 20, 'City': 'Hyderabad'},

    {'Name': 'Sachin', 'Age': 21, 'City': 'Pune'},

    {'Name': 'Lucy', 'Age': 40, 'City': 'New York'}

]

# Writing to CSV using DictWriter

with open('dictwriter-example.csv', 'w', newline='') as file:

    fieldnames = ['Name', 'Age', 'City']

    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()        # Write header row

    writer.writerows(data)      # Write all rows

Output:

Output

Name,Age,City

John,20,Hyderabad

Sachin,21,Pune

Lucy,40,New York

Explanation:

Initially, the csv module is imported to facilitate interactions with CSV files. Following this, a collection of dictionaries is constructed, where each individual row of data is depicted as a dictionary, with the keys corresponding to the names of the columns. The file is then accessed in write ('w') mode through the use of open, and a DictWriter object is instantiated.

2) Write CSV Files Using the csv.writer Method

In Python, the csv.writer function enables users to write data into CSV files, typically organized as lists or tuples, adopting a row-by-row method for insertion. This function is included in Python’s standard csv module and offers an uncomplicated means to output tabular data.

Syntax:

It has the following syntax:

Example

csv.writer(file, dialect='excel', **fmtparams)

Parameters:

  • file: The file object opened in write ('w') or append ('a') mode.
  • dialect: (Optional) Controls formatting (default is 'excel').
  • **fmtparams: Optional formatting options like delimiter, quotechar, lineterminator, etc.
  • Python Example to Write CSV Files using the csv.writer Method

To illustrate the process of generating CSV files with the csv.writer method in Python, let's consider an example.

Example

#importing csv module

import csv

# List of rows to write means each row is a list

rows = [

    ['Name', 'Age', 'City'],

    ['Rohan', 22, 'New Delhi'],

    ['Abhay', 23, 'Noida'],

    ['Vivek', 24, 'Gurgaon']

]

with open('writer-output.csv', 'w', newline='') as file:

    writer = csv.writer(file)

    writer.writerows(rows)

# Read and print contents

with open('writer-output.csv', 'r') as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Output:

Output

['Name', 'Age', 'City']

['Rohan', '22', 'New Delhi']

['Abhay', '23', 'Noida']

['Vivek', '24', 'Gurgaon']

Explanation:

In the preceding illustration, every data row represented in lists or tuples can be written into a CSV file utilizing the csv.writer function. Initially, a library is imported that specifies the name of the CSV file. Following this, a collection of rows is established, which is subsequently populated with information such as names, ages, and cities that were originally held separately.

Advanced CSV Writing in Python

Although it is well understood that csv.writer and csv.DictWriter suffice for the majority of typical scenarios in their fundamental application, the csv module in Python also encompasses several advanced functionalities that cater to more intricate requirements for CSV writing. These advanced features include the ability to define custom delimiters, manage quoting options, append additional data, and address situations involving missing or surplus fields.

1) Custom Delimiter

By default, CSV files utilize a comma (,) as their delimiter. However, it is possible to modify this to any other character, such as a semicolon or a tab, by specifying the delimiter parameter.

Example

Example

#importing csv

import csv

# List of rows to write (each row is a list)

data = [

    ['Product', 'Price', 'Stock'],

    ['Pen', 2.5, 100],

    ['Notebook', 3.0, 50]

]

# Writing to CSV using csv.writer

with open('semicolon-output.csv', 'w', newline='') as file:

    writer = csv.writer(file, delimiter=';')

    writer.writerows(data)

Output:

Output

Product;Price;Stock

Pen;2.5;100

Notebook;3.0;50

Explanation:

In the preceding illustration, the provided code generates a CSV file titled semicolon-output.csv containing a compilation of product information. It employs the csv.writer method, utilizing a semicolon (;) as the delimiter rather than the standard comma, which is typically the default separator. Each sublist present in the data transforms into a corresponding row within the CSV file, with the values delineated by semicolons. This formatting is frequently adopted in areas where commas serve as decimal markers.

2) Quoting Fields

CSV fields that contain special characters like commas or quotes can be enclosed in quotes. Use quoting for more granular control with the following options:

  • QUOTE-MINIMAL - Using this to quote only when necessary (default)
  • QUOTE-ALL - Used to quote all fields
  • QUOTE-NONNUMERIC - It is used to quote all non-numeric fields
  • QUOTE-NONE - It is used to avoid quoting; never quote (requires escape characters)

Example

Example

import csv

# List of rows to write (each row is a list)

data = [

    ['Name', 'Comment'],

    ['Abhay', 'Hello Sir, the work is done"'],

    ['Vivek', 'Great Work']

]

#Writing to CSV with all fields quoted

with open('quoted-output.csv', 'w', newline='') as file:

    writer = csv.writer(file, quoting=csv.QUOTE-ALL)

    writer.writerows(data)

print("CSV file 'quoted-output.csv' created successfully!")

#let's print the content after reading the file

with open('quoted-output.csv', 'r') as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Output:

Output

CSV file 'quoted-output.csv' created successfully!

['Name', 'Comment']

['Abhay', 'Hello Sir, the work is done"']

['Vivek', 'Great Work']

Explanation:

In this example, data is being written to a CSV file with the CSV.QUOTE_ALL setting enabled. This configuration ensures that every field is enclosed in double quotes. This approach is particularly useful when fields contain delimiters like commas or quotation marks that could be misinterpreted. For example, if a comment includes double quotes, they will be escaped by duplicating them in scenarios where the text is enclosed in double quotes.

3) Handling Missing Fields in DictWriter

When employing the DictWriter class, you can handle missing keys by using the restval parameter to assign a default value.

Example

import csv

data = [

    {'Name': 'Lucy', 'Age': 30},  # 'City' is missing

    {'Name': 'Peter', 'Age': 25, 'City': 'Miami'}

]

with open('dict-missing-fields.csv', 'w', newline='') as file:

    fieldnames = ['Name', 'Age', 'City']

    writer = csv.DictWriter(file, fieldnames=fieldnames, restval='N/A')

    writer.writeheader()

    writer.writerows(data)

Output:

Output

Name,Age,City

Lucy,30,N/A

Peter,25,Miami

Explanation:

In this illustration, the CSV.DictWriter module is employed to fill a CSV file, assigning a default value of 'N/A' for any fields that are absent, utilizing the restval parameter. When a dictionary lacks a specific field, for instance, 'City' for the entry corresponding to Lucy, that particular field will be substituted with 'N/A' automatically. Default values are applied for certain records, like Lucy, while other records, such as Peter, who possesses complete field information, have their values written out as usual.

Conclusion

In this guide, we explored the process of creating CSV files using Python. We examined multiple techniques for writing CSV files. We gained insights into the functionalities of CSV.DictWriter and csv.writer. Additionally, we reviewed some advanced strategies that enable us to produce efficient CSV files in Python.

Input Required

This code uses input(). Please provide values below: