Write CSV Files using csv.DictWriter in Python

To write CSV files using csv.DictWriter in Python, we use the csv module, which provides built-in functionality to work with CSV files efficiently. The csv.DictWriter class allows writing data as dictionaries where each dictionary key corresponds to a column in the CSV file.


Examples to Write CSV Files

1. Writing a Simple CSV File Using csv.DictWriter

In this example, we will create a CSV file named employees.csv containing employee details such as name, age, and department. We will use csv.DictWriter to write multiple dictionary records into the file.

main.py

</>
Copy
import csv

# Defining CSV file name
filename = "employees.csv"

# Defining the field names (CSV column headers)
fieldnames = ["name", "age", "department"]

# Data to be written (list of dictionaries)
employees = [
    {"name": "Alice", "age": 30, "department": "HR"},
    {"name": "Bob", "age": 25, "department": "IT"},
    {"name": "Charlie", "age": 35, "department": "Finance"}
]

# Writing to CSV file
with open(filename, mode="w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    # Writing the header
    writer.writeheader()

    # Writing data rows
    writer.writerows(employees)

print("CSV file written successfully.")

Explanation:

  1. We import the csv module to handle CSV file operations.
  2. We define the file name as employees.csv.
  3. The fieldnames list contains the column names of the CSV file.
  4. The employees list holds dictionary records, where each dictionary represents a row.
  5. We open the file in write mode using open(filename, mode="w", newline="").
  6. We create a DictWriter object, passing the field names.
  7. writeheader() writes the column headers to the file.
  8. writerows(employees) writes all dictionary records into the CSV file.

Output File Content:

2. Writing a CSV File with Custom Delimiter

By default, CSV files use a comma (,) as a separator. In this example, we will change the delimiter to a semicolon (;) using the delimiter parameter of csv.DictWriter.

main.py

</>
Copy
import csv

# Defining CSV file name
filename = "students.csv"

# Defining the field names
fieldnames = ["id", "name", "grade"]

# Data to be written
students = [
    {"id": 101, "name": "John", "grade": "A"},
    {"id": 102, "name": "Emma", "grade": "B"},
    {"id": 103, "name": "Sophia", "grade": "A"}
]

# Writing to CSV file with a custom delimiter
with open(filename, mode="w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames, delimiter=";")

    # Writing the header
    writer.writeheader()

    # Writing data rows
    writer.writerows(students)

print("CSV file written with semicolon delimiter.")

Explanation:

  1. We define the CSV filename as students.csv.
  2. The fieldnames list specifies column headers.
  3. We create a list of student records using dictionaries.
  4. We open the file in write mode and pass delimiter=";" in DictWriter.
  5. The header row is written using writeheader().
  6. The data rows are added using writerows(students).

Output File Content:

3. Appending Data to an Existing CSV File

In this example, we will append new records to an existing CSV file employees.csv (that we created in the first example) using the append mode (a).

main.py

</>
Copy
import csv

# Defining CSV file name
filename = "employees.csv"

# New data to append
new_employees = [
    {"name": "David", "age": 40, "department": "Marketing"},
    {"name": "Eve", "age": 28, "department": "Sales"}
]

# Appending to the existing file
with open(filename, mode="a", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "age", "department"])

    # Writing data rows without rewriting the header
    writer.writerows(new_employees)

print("New records appended successfully.")

Explanation:

  1. We open the employees.csv file in append mode using mode="a".
  2. We define new employee records as dictionaries.
  3. We create a DictWriter object with the same field names.
  4. We call writerows(new_employees) to append new rows.

Output File Content (After Appending):

Conclusion

The csv.DictWriter class provides a simple way to write structured data to CSV files in Python. We explored writing new CSV files, using custom delimiters, and appending data to existing files.