Reading and Writing CSV Files in Python

Python Logo

CSV (Comma-Separated Values) is a common format for storing tabular data. Python's built-in `csv` module makes it easy to read from and write to CSV files.

Reading a CSV File

The `csv.reader` object allows you to iterate over rows in the CSV file. Each row will be a list of strings.

import csv

with open('data.csv', mode='r', newline='') as file:
    csv_reader = csv.reader(file)
    header = next(csv_reader) # Skip the header row
    print(f'Header: {header}')
    for row in csv_reader:
        # row is a list of strings, e.g., ['1', 'Alice', '30']
        print(f'ID: {row[0]}, Name: {row[1]}, Age: {row[2]}')

Reading a CSV into a Dictionary

For easier access to data by column name, use `csv.DictReader`. Each row becomes a dictionary where the keys are the header names.

import csv

with open('data.csv', mode='r', newline='') as file:
    csv_reader = csv.DictReader(file)
    for row in csv_reader:
        # row is a dictionary, e.g., {'ID': '1', 'Name': 'Alice', 'Age': '30'}
        print(f'Name: {row["Name"]}')

Writing to a CSV File

Use `csv.writer` to write data to a CSV file. The `writerow()` method writes a single row, and `writerows()` writes multiple rows.

import csv

header = ['Name', 'Department', 'Salary']
data = [
    ['Alice', 'Engineering', 80000],
    ['Bob', 'Marketing', 65000]
]

with open('employees.csv', mode='w', newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerow(header)
    csv_writer.writerows(data)

print('CSV file written successfully.')

Pro Tip: For more complex data manipulation, consider using the powerful `pandas` library, which can read and write CSV files with a single command (`pd.read_csv()`, `df.to_csv()`).

Comments