Write CSV File

Write a few sample rows to a CSV file.

BeginnerTopic: File Handling Programs
Back

Python Write CSV File Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding Write CSV File

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents