Camkode
Camkode

Reading and Writing CSV Files in Python: A Step-by-Step Guide

Posted by Kosal

Reading and Writing CSV Files in Python: A Step-by-Step Guide

CSV (Comma-Separated Values) files are a popular format for storing and exchanging tabular data. Python provides a built-in module called csv that simplifies the process of reading from and writing to CSV files. In this tutorial, we'll explore how to use the csv module to handle CSV files in Python.

Reading CSV Files

Basic CSV Reading:

To begin reading a CSV file, you first need to open it using the open() function. Then, create a csv.reader object to iterate over the rows:

import csv

# Specify the path to the CSV file
csv_file_path = 'path/to/your/file.csv'

# Open the CSV file for reading
with open(csv_file_path, 'r') as file:
    # Create a CSV reader object
    csv_reader = csv.reader(file)

    # Read and process each row in the CSV file
    for row in csv_reader:
        print(row)

This code will print each row of the CSV file as a list.

Reading with Headers:

If your CSV file has headers, you can use csv.DictReader for a more convenient way to access data:

import csv

# Specify the path to the CSV file
csv_file_path = 'path/to/your/file.csv'

# Open the CSV file for reading
with open(csv_file_path, 'r') as file:
    # Create a CSV DictReader object for reading with headers
    csv_reader = csv.DictReader(file)

    # Read and process each row in the CSV file
    for row in csv_reader:
        print(row)

Here, each row is represented as a dictionary, with keys corresponding to the header names.

Writing to CSV Files

Basic CSV Writing:

To write data to a new CSV file, you need to open it in write mode ('w') and create a csv.writer object:

import csv

# Specify the path to the new CSV file
csv_file_path = 'path/to/your/new_file.csv'

# Data to be written to the CSV file
data_to_write = [
    ['Name', 'Age', 'City'],
    ['Alice', 25, 'New York'],
    ['Bob', 30, 'San Francisco'],
    ['Charlie', 22, 'Los Angeles']
]

# Open the CSV file for writing
with open(csv_file_path, 'w', newline='') as file:
    # Create a CSV writer object
    csv_writer = csv.writer(file)

    # Write the data to the CSV file
    csv_writer.writerows(data_to_write)

print(f"Data has been written to {csv_file_path}")

This example writes a list of lists to a new CSV file. Adjust the data_to_write variable and file path according to your requirements.

Conclusion

Reading and writing CSV files in Python is made easy with the csv module. Whether you are dealing with data analysis, data migration, or any other task involving tabular data, mastering CSV handling in Python is a valuable skill. With the techniques outlined in this guide, you're well-equipped to work with CSV files efficiently in your Python projects. Happy coding!