CSV (Comma-Separated Values) files are widely used for exporting data from spreadsheets and databases. Python's csv module makes it easy to read and write these files. In this tutorial, you will learn how to use the csv module to efficiently manipulate CSV files.

What is a CSV File?

A CSV file is a text file where values are separated by commas (or another delimiter, such as a semicolon). Each line in the file corresponds to a record, and each value separated by a comma corresponds to a field within that record.

Example CSV File:

id,product,category,quantity,price,added_on
1,beans,food,20,100,01-01-2020
2,rice,food,20,150,01-02-2020
3,onion,food,20,120,01-01-2020
4,beer,beverage,20,160,01-04-2020
5,juice,beverage,20,170,01-04-2020
6,milk,beverage,20,120,01-05-2020

Key Methods of the csv Module

The table below shows some useful methods of the csv module:

Method Description
csv.reader() Returns an object that reads the CSV file line by line.
csv.writer() Returns an object that writes data to a CSV file.
csv.DictReader() Reads the CSV file as a dictionary, where the first line becomes the keys.
csv.DictWriter() Writes data to a CSV file from a dictionary.
csv.register_dialect() Registers a CSV "dialect" to handle different file formats.
csv.list_dialects() Lists registered dialects.
csv.field_size_limit() Returns the maximum allowed size for a field.

Reading CSV Files

The simplest way to read a CSV file is by using csv.reader():

Example 1: Reading a CSV File

import csv

with open('products.csv', newline='', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)

Output:

['id', 'product', 'category', 'quantity', 'price', 'added_on']
['1', 'beans', 'food', '20', '100', '01-01-2020']
['2', 'rice', 'food', '20', '150', '01-02-2020']
...

Example 2: Reading a CSV File with a Different Delimiter

If the CSV file uses a different delimiter, such as ; or /, you can specify it:

import csv

with open('products_delimiter.csv', newline='', encoding='utf-8') as file:
    csv_reader = csv.reader(file, delimiter='/')
    for row in csv_reader:
        print(row)

This allows csv.reader() to correctly handle files using custom delimiters.

Example 3: Reading a CSV File as a Dictionary

We can use csv.DictReader() to read each row as a dictionary, where the keys are the file headers.

import csv

with open('products.csv', newline='', encoding='utf-8') as file:
    csv_reader = csv.DictReader(file)
    for row in csv_reader:
        print(dict(row))

Output:

{'id': '1', 'product': 'beans', 'category': 'food', 'quantity': '20', 'price': '100', 'added_on': '01-01-2020'}
{'id': '2', 'product': 'rice', 'category': 'food', 'quantity': '20', 'price': '150', 'added_on': '01-02-2020'}
...

Writing to CSV Files

To write data to a CSV file, we use the csv.writer() function. Let's create a new CSV file and write data to it.

Example 4: Writing to a CSV File

import csv

with open('new_products.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["id", "product", "category", "quantity", "price", "added_on"])
    writer.writerow([1, "beans", "food", 20, 100, "01-01-2020"])
    writer.writerow([2, "rice", "food", 20, 150, "01-02-2020"])

Output in new_products.csv:

id,product,category,quantity,price,added_on
1,beans,food,20,100,01-01-2020
2,rice,food,20,150,01-02-2020

Example 5: Writing a CSV File from a Dictionary

Another way to write data is by using csv.DictWriter(), which allows writing from dictionaries.

import csv

with open('products_dict.csv', 'w', newline='', encoding='utf-8') as file:
    fields = ["id", "product", "category", "quantity", "price", "added_on"]
    writer = csv.DictWriter(file, fieldnames=fields)
    
    writer.writeheader()  # Write the header
    writer.writerow({"id": 1, "product": "beans", "category": "food", "quantity": 20, "price": 100, "added_on": "01-01-2020"})
    writer.writerow({"id": 2, "product": "rice", "category": "food", "quantity": 20, "price": 150, "added_on": "01-02-2020"})

Output in products_dict.csv:

id,product,category,quantity,price,added_on
1,beans,food,20,100,01-01-2020
2,rice,food,20,150,01-02-2020

Conclusion

In this tutorial, we explored how to use Python's csv module to read and write CSV files. We used different examples to illustrate how to handle simple CSV files, customized delimiters, and working with data in dictionary format. Working with CSV files is an essential skill for any developer dealing with data, making it much easier to process large volumes of information efficiently.

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/working-with-csv-files-in-python/