0
0
Pythonprogramming~5 mins

Reading and writing CSV data in Python

Choose your learning style9 modes available
Introduction

CSV files store data in a simple table format. Reading and writing CSV lets your program work with this common data type easily.

You want to save a list of contacts to a file to open later in a spreadsheet.
You need to read data from a CSV report to analyze it in your program.
You want to export data from your program so others can use it in Excel or Google Sheets.
You have data from a website or database in CSV format and want to process it in Python.
Syntax
Python
import csv

# Reading CSV
with open('file.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# Writing CSV
with open('file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', '30'])

Use csv.reader to read rows from a CSV file.

Use csv.writer to write rows to a CSV file.

Examples
This reads each row from data.csv and prints it as a list of strings.
Python
import csv

with open('data.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
This writes two rows to output.csv: a header and one data row.
Python
import csv

with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['City', 'Population'])
    writer.writerow(['Paris', '2148000'])
Using DictReader reads CSV rows as dictionaries, so you can access columns by name.
Python
import csv

with open('data.csv', 'r', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['Name'], row['Age'])
Using DictWriter writes rows as dictionaries with named columns.
Python
import csv

with open('output.csv', 'w', newline='') as file:
    fieldnames = ['Name', 'Age']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'Bob', 'Age': 25})
Sample Program

This program first writes two rows of data to people.csv. Then it reads the file and prints each row as a list.

Python
import csv

# Write sample data to CSV
with open('people.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 30])
    writer.writerow(['Bob', 25])

# Read and print the CSV data
with open('people.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
OutputSuccess
Important Notes

Always open CSV files with newline='' to avoid extra blank lines on some systems.

CSV data is text, so numbers are read as strings unless converted.

Use DictReader and DictWriter for easier column access by name.

Summary

CSV files store data in rows and columns separated by commas.

Use Python's csv module to read and write CSV files easily.

Reading returns rows as lists or dictionaries; writing sends lists or dictionaries as rows.