How to Read and Write CSV Files in Python

How to Read and Write CSV Files in Python

In this in-depth guide, we’ll cover everything you need to know about CSV files – from understanding the definition of Comma Separated Values files to reading, discussing delimiters and quote characters, and writing CSV files.

We’ll cap it off by delving into how to leverage the pandas library in Python to read files with ease.

Whether you’re a beginner or seasoned coder, this comprehensive tutorial will equip you with the knowledge and skills to handle Comma Separated Values file files effectively. Join us on this learning journey and unlock the power of Python for handling CSV data.

Tutorial Video

Explanation

A CSV file (Comma Separated Values file) is a plain text file that organizes tabular data. Each piece of data is separated by a comma, and the first row typically contains column names. Here’s an example structure:

Column 1 Name, Column 2 Name, Column 3 Name

First Row Data 1, First Row Data 2, First Row Data

Second Row Data 1, Second Row Data 2, Second Row Data 3 …

Python Code

Reading CSV Files

# Function to read a CSV file using Python's built-in CSV module. 

import csv

def read_csv_basic(filename):
    """
    Args:
    filename (str): The name of the CSV file to be read.
    Returns:
    list: A list of dictionaries, where each dictionary represents a row in the CSV file.
    """
    
    data = []
    
    with open(filename, mode='r', newline='') as file:
        reader = csv.DictReader(file)
        for row in reader:
            data.append(row)
            
    return data

print("Reading CSV file using basic method:")
basic_data = read_csv_basic('customers-data.csv')
print(basic_data)


#  Function to read a CSV file with custom delimiter and quote characters.

def read_csv_custom(filename, delimiter=',', quotechar='"'):
    """
    Function to read a CSV file with custom delimiter and quote characters.

    Args:
    filename (str): The name of the CSV file to be read.
    delimiter (str): The character used to separate fields in the CSV file.
    quotechar (str): The character used to quote fields containing special characters.

    Returns:
    list: A list of dictionaries, where each dictionary represents a row in the CSV file.
    """
    data = []
    
    with open(filename, mode='r', newline='') as file:
        reader = csv.DictReader(file, delimiter=delimiter, quotechar=quotechar)
        for row in reader:
            data.append(row)
            
    return data
    
print("\nReading CSV file using custom method:")
custom_data = read_csv_custom('example.csv', delimiter=';', quotechar='\'')
print(custom_data)
    


Writing CSV Files

# Writing CSV Files

def write_csv(filename, data, fieldnames):
    
    """
    Function to write data to a CSV file.

    Args:
    filename (str): The name of the CSV file to be written.
    data (list of dict): The data to be written to the CSV file.
    fieldnames (list): The field names for the CSV file.

    Returns:
    None
    """
    
    with open(filename, mode='w', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            writer.writerow(row)

# Example usage of writing CSV files
data_to_write = [
    {'Name': 'John', 'Age': 25, 'City': 'New York'},
    {'Name': 'Emma', 'Age': 30, 'City': 'Los Angeles'},
    {'Name': 'Ryan', 'Age': 35, 'City': 'Chicago'}
]
fieldnames = ['Name', 'Age', 'City']
print("\nWriting data to CSV file:")
write_csv('output.csv', data_to_write, fieldnames)

Using pandas (Upcoming Tutorial On YouTube)

import pandas as pd

# Read CSV into a DataFrame
df = pd.read_csv('people-100.csv')
df