Writing CSV files in Python

Assume the learner will use the built-in csv module and basic file operations.


1) Create Simple CSV

Write a CSV file students.csv with:

name,age
Alice,20
Bob,22

2) Write with Header Only

Create products.csv with headers only:

id,product,price

3) Write 3 Rows

Ask the user for 3 product entries (id, product, price) and write them to products.csv.


4) Append a Row

Write code that appends this row to an existing CSV:

Charlie,25,Vancouver

5) Write List of Lists

Given a list:

Write it to people.csv with header name,age.


6) Write Using DictWriter

Create employees.csv with fields name,dept,salary, and write 3 dictionary rows using csv.DictWriter.


7) Write with Fieldnames from User

Ask user for column names (comma-separated) and create header in a new CSV.


8) Write Numeric Data

Create scores.csv with:


9) Write Mixed Data Types

Write a CSV where one column is text and one is number.

Example row:


10) Write Multiple CSV Files

Ask the user for n, then write n CSV files named file1.csv, file2.csv, …, each with sample data.


11) Write with Quoting

Write a CSV where fields are quoted even if not necessary (use quoting options).


12) Write with Tab Delimiter

Write a file tabdata.csv where columns are separated by tabs instead of commas.


13) Predefined Header + Rows

Write a CSV countries.csv with:


14) Write CSV Using writerow in Loop

Ask for 5 names and write them one per line with a serial number.


15) Write and Read Back

Create a CSV, then immediately open it and print its contents in the same script.


16) Write to CSV from a List of Dicts

Given:

Write it to people2.csv.


17) Append With DictWriter

Add a new employee row to employees.csv using DictWriter in append mode.


18) Save Strings as Rows

Given a list of strings like:

Write each as a separate row in fruits.csv.


19) Write CSV with Computed Values

Ask user for numbers, compute squares, and write pairs in CSV.

Example CSV:


20) Write CSV with Random Data

Generate 10 random integers and write them to random.csv with columns:


🧠 Functions / Modules You’ll Use

Task
Module / Method

Write CSV

csv.writer

Write with header

csv.writer / writerow()

Write dicts

csv.DictWriter, writeheader()

Append rows

open file in "a" mode

Quoting

csv.QUOTE_ALL

Custom delimiter

csv.writer(..., delimiter="\t")


📌 Starter Code Snippet (Basic Writer)


📌 DictWriter Example


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated