Python CSV: Read and Write CSV files

1. What is a CSV File

A CSV (Comma-Separated Values) file stores tabular data in plain text, where each line represents a row and values are separated by commas.

Example:

name,age,city
Alice,25,New York
Bob,30,London

2. Reading a CSV File Using csv.reader

import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Reads each row as a list of values.


3. Skipping Header Row

import csv

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

Useful when the first row contains column names.


4. Reading CSV as Dictionary (csv.DictReader)

Each row is read as an ordered dictionary mapped to column headers.


5. Writing to a CSV File Using csv.writer

Creates and writes rows to a CSV file.


6. Writing Multiple Rows at Once

Efficient for bulk data writing.


7. Writing Dictionaries Using csv.DictWriter

Ensures structured column mapping.


8. Custom Delimiters and Quoting

CSV supports configurable delimiters for complex data formats.


9. Appending Data to an Existing CSV

"a" mode appends data without overwriting existing rows.


10. Reading CSV Using pandas (Advanced)

Pandas provides high-level, efficient CSV data manipulation for analytics and ML workflows.


Last updated