Skip to content

Reading and writing of CSV files

CSV files (Comma Separated Values) are plain text files that store tabular data. Each line represents a row of data and each value is separated by commas (or another delimiter like ;). They are widely used for exporting data from spreadsheets or databases.

We have the following project structure:

  • Directorysrc
    • read_csv.py
    • write_csv.py
    • rewrite_csv.py
  • Directorydocs
    • products.csv

To read CSV files, Python provides the built-in csv module. This module allows you to iterate over rows, access columns by index or name, and handle different delimiters.

read_csv.py
import csv
with open ('./docs/products.csv', 'r') as file:
    csv_reader = csv.DictReader(file)
    for row in csv_reader:
        print(row)

This script opens an existing CSV file and adds a new row with product data. Uses the ‘a’ mode to append at the end without deleting the previous content.

write_csv.py
import csv
# Data to add
new_product = {'name': 'Keyboard', 'price': '45'}
# Add a new row at the end of the file
with open('./docs/products.csv', 'a', newline='') as file:
fieldnames = ['name', 'price']
writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write a new line
writer.writerow(new_product)

This script overwrites a CSV file with a new list of products. Utilizes the ‘w’ mode to start from scratch, including the header.

overwrite_csv.py
import csv
# List of products to overwrite the file completely
products = [
{'name': 'Monitor', 'price': '200'},
{'name': 'Headphones','price': '80'}
]
# Overwrite the file with new data
with open('./docs/products.csv', 'w', newline='') as file:
    fieldnames = ['name', 'price']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write header and then data
writer.writeheader()
writer.writerows(products)