Write CSV File

Write a few sample rows to a CSV file.

PythonBeginner
Python
# Program to write to a CSV file

import csv

filename = input("Enter CSV filename to write: ")

rows = [
    ["name", "age"],
    ["Alice", "25"],
    ["Bob", "30"],
]

with open(filename, "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

print("CSV data written to", filename)

Output

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

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