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 browser1# Program to write to a CSV file23import csv45filename = input("Enter CSV filename to write: ")67rows = [8 ["name", "age"],9 ["Alice", "25"],10 ["Bob", "30"],11]1213with open(filename, "w", newline="", encoding="utf-8") as f:14 writer = csv.writer(f)15 writer.writerows(rows)1617print("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.