Python Working with CSV Files


Working with CSV Files in Python

CSV (Comma-Separated Values) files are a common format for storing tabular data, making them easy to read and write in Python. Python provides a built-in module called csv that simplifies the process of reading from and writing to CSV files. This guide will cover the basics of working with CSV files in Python, including reading, writing, and handling different CSV formats.

Importing the CSV Module

Before you can work with CSV files, you need to import the csv module:

import csv

Reading CSV Files

1. Reading a CSV File

You can read CSV files using the csv.reader() function. This function returns an iterable object that can be used to iterate over rows in the CSV file.

# Reading a CSV file with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) # Each row is a list of values

2. Skipping the Header

If your CSV file contains a header row, you may want to skip it. You can do this using the next() function.

with open('data.csv', 'r') as file: reader = csv.reader(file) header = next(reader) # Skip the header row for row in reader: print(row)

3. Reading CSV Files into a Dictionary

If you want to read CSV data into a dictionary format, you can use the csv.DictReader() class. This allows you to access each row using column names as keys.

with open('data.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row['column_name']) # Access data by column name

Writing to CSV Files

1. Writing a CSV File

You can write to CSV files using the csv.writer() function. This function creates a writer object that can write data to a CSV file.

# Writing to a CSV file data = [ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'], ['Charlie', 35, 'Chicago'], ] with open('output.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data) # Write multiple rows

2. Writing a Dictionary to a CSV File

If you want to write data stored in dictionaries, use the csv.DictWriter() class. You need to specify the fieldnames (header) when creating the writer object.

# Writing a list of dictionaries to a CSV file data = [ {'Name': 'Alice', 'Age': 30, 'City': 'New York'}, {'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'}, {'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}, ] with open('output.csv', 'w', newline='') as file: fieldnames = ['Name', 'Age', 'City'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() # Write the header writer.writerows(data) # Write the data

Customizing the CSV Format

You can customize the delimiter, quote character, and other parameters when working with CSV files. By default, the delimiter is a comma (,), but you can change it if necessary.

# Using a semicolon as a delimiter with open('data.csv', 'r') as file: reader = csv.reader(file, delimiter=';') for row in reader: print(row)

Handling Errors

It's essential to handle potential errors when working with CSV files, such as file not found or reading issues, using try-except blocks.

try: with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) except FileNotFoundError: print("The file was not found.") except Exception as e: print(f"An error occurred: {e}")

Summary

  • Import the CSV Module: Use import csv to work with CSV files.
  • Reading CSV Files:
    • Use csv.reader() for reading rows.
    • Use csv.DictReader() for reading rows into dictionaries.
  • Writing CSV Files:
    • Use csv.writer() for writing rows.
    • Use csv.DictWriter() for writing dictionaries.
  • Customizing Format: Change delimiters and quote characters as needed.
  • Error Handling: Use try-except blocks to manage file-related errors.

Working with CSV files in Python is straightforward and efficient, thanks to the built-in csv module, making it easy to read, write, and manipulate tabular data!