Editor

Python Program to Write a CSV File

Beginner · File handling

This program saves a table of data to a CSV (comma separated values) file with Python's csv module, so it can be opened in Excel or Google Sheets. It writes a header row and one row per product, then prints the file to show exactly what was saved.

Program

write_csv_file.py
import csv
products = [
["Pen", 10, 25],
["Notebook", 45, 10],
["Geometry box, steel", 120, 4],
]
with open("stock.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["item", "price", "quantity"]) # the header row
for product in products:
writer.writerow(product) # numbers are turned into text for you
print("Saved", len(products), "products to stock.csv")
# Show the file as plain text
with open("stock.csv", "r") as f:
print(f.read(), end="")
Output
Saved 3 products to stock.csv
item,price,quantity
Pen,10,25
Notebook,45,10
"Geometry box, steel",120,4

How it works

  1. Each product is a list, and writer.writerow() writes one list as one line of the file, with commas between the values.
  2. Numbers such as 10 and 25 are turned into text automatically, unlike f.write(), which only accepts strings.
  3. The value "Geometry box, steel" contains a comma, so the csv module wraps it in quotes, which keeps it in one column when the file is read.
  4. newline="" is how the csv module asks for the file to be opened; without it, Windows shows a blank line between the rows.

Other ways to write it

Using writerows()

Using writerows()
import csv
rows = [["item", "price"], ["Pen", 10], ["Eraser", 5], ["Ruler", 15]]
with open("stock.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows) # every row in one call
with open("stock.csv", "r") as f:
print(f.read(), end="")
Output
item,price
Pen,10
Eraser,5
Ruler,15

writerows() takes a list of rows and writes them all at once, the header included.

Using csv.DictWriter

Using csv.DictWriter
import csv
students = [
{"name": "Aarav", "marks": 88},
{"name": "Diya", "marks": 95},
]
with open("students.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "marks"])
writer.writeheader() # writes: name,marks
writer.writerows(students)
with open("students.csv", "r") as f:
print(f.read(), end="")
Output
name,marks
Aarav,88
Diya,95

DictWriter writes dictionaries, putting each value in the column named by its key, and writeheader() writes the column names from fieldnames.

Try it yourself

Add a "total" column that holds price times quantity for each product.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises