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
Saved 3 products to stock.csv item,price,quantity Pen,10,25 Notebook,45,10 "Geometry box, steel",120,4
How it works
- Each product is a list, and
writer.writerow()writes one list as one line of the file, with commas between the values. - Numbers such as 10 and 25 are turned into text automatically, unlike
f.write(), which only accepts strings. - 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.
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()
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
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.
Related programs
- Read a CSV File
- Store and Search User IDs and Passwords in a CSV File
- Write to a File
- Read and Write a JSON File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises