Write CSV File in Python

Write a few sample rows to a CSV file.

BeginnerFile Handling ProgramsExample 5 of 20
write-csv-file.py
Run in browser
1# Program to write to a CSV file
2
3import csv
4
5filename = input("Enter CSV filename to write: ")
6
7rows = [
8 ["name", "age"],
9 ["Alice", "25"],
10 ["Bob", "30"],
11]
12
13with open(filename, "w", newline="", encoding="utf-8") as f:
14 writer = csv.writer(f)
15 writer.writerows(rows)
16
17print("CSV data written to", filename)

Output

Enter CSV filename to write: data.csv
CSV data written to data.csv

What's going on

csv.writer.writerows writes a list of rows (each a list of strings) into a CSV file.