How to Write CSV File in Python: Simple Guide with Examples
To write a CSV file in Python, use the
csv module's writer object. Open a file in write mode, create a writer with csv.writer(file), then use writer.writerow() to add rows.Syntax
Here is the basic syntax to write rows to a CSV file using Python's csv module:
- Open a file in write mode with
open('filename.csv', 'w', newline=''). - Create a CSV writer object with
csv.writer(file). - Use
writer.writerow()to write a single row (list of values). - Use
writer.writerows()to write multiple rows at once.
python
import csv with open('output.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age', 'City']) # Write header row writer.writerow(['Alice', 30, 'New York']) # Write one data row writer.writerows([ ['Bob', 25, 'Los Angeles'], ['Charlie', 35, 'Chicago'] ]) # Write multiple rows
Example
This example writes a CSV file named people.csv with a header and three rows of data. It shows how to open the file, create the writer, and write rows.
python
import csv with open('people.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age', 'City']) writer.writerow(['Alice', 30, 'New York']) writer.writerow(['Bob', 25, 'Los Angeles']) writer.writerow(['Charlie', 35, 'Chicago'])
Common Pitfalls
Common mistakes when writing CSV files in Python include:
- Not using
newline=''inopen(), which can cause extra blank lines on some systems. - Forgetting to open the file in write mode
'w'. - Passing strings instead of lists to
writer.writerow(). - Not closing the file (using
withhandles this automatically).
python
import csv # Wrong: missing newline='' causes blank lines on Windows with open('wrong.csv', 'w') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age']) # Right: use newline='' to avoid blank lines with open('right.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age'])
Quick Reference
Summary tips for writing CSV files in Python:
- Always import the
csvmodule. - Open files with
newline=''to avoid blank lines. - Use
writer.writerow()for single rows andwriter.writerows()for multiple rows. - Pass rows as lists or tuples, not strings.
- Use
withto handle file closing automatically.
Key Takeaways
Use the csv module's writer object to write rows to a CSV file.
Always open the file with newline='' to prevent extra blank lines.
Write rows as lists or tuples using writer.writerow() or writer.writerows().
Use with statement to automatically close the file after writing.
Avoid passing strings directly to writer.writerow(); use iterable of values instead.