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
Reading a CSV File
Section titled “Reading a CSV File”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.
import csv
with open ('./docs/products.csv', 'r') as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(row)
Writing to a CSV File
Section titled “Writing to a CSV File”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.
import csv
# Data to addnew_product = {'name': 'Keyboard', 'price': '45'}
# Add a new row at the end of the filewith open('./docs/products.csv', 'a', newline='') as file:fieldnames = ['name', 'price']writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write a new linewriter.writerow(new_product)
Overwrite a CSV file
Section titled “Overwrite a CSV file”This script overwrites a CSV file with a new list of products. Utilizes the ‘w’ mode to start from scratch, including the header.
import csv
# List of products to overwrite the file completelyproducts = [{'name': 'Monitor', 'price': '200'},{'name': 'Headphones','price': '80'}]
# Overwrite the file with new datawith open('./docs/products.csv', 'w', newline='') as file: fieldnames = ['name', 'price'] writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write header and then datawriter.writeheader()writer.writerows(products)