CSV files store data in a simple table format. Learning to work with them helps you read and save data easily.
0
0
Working with CSV files in Python
Introduction
You want to save a list of contacts from your program to a file.
You need to read data from a spreadsheet saved as CSV.
You want to share data with others in a simple text format.
You want to process data exported from a database or website.
You want to automate reading or writing data in a format many programs understand.
Syntax
Python
import csv # Reading CSV file with open('file.csv', newline='') as file: reader = csv.reader(file) for row in reader: print(row) # Writing CSV file with open('file.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age']) writer.writerow(['Alice', 30])
Use newline='' when opening files to avoid extra blank lines on some systems.
csv.reader reads rows as lists of strings.
Examples
This reads each row from
data.csv and prints it as a list.Python
import csv with open('data.csv', newline='') as file: reader = csv.reader(file) for row in reader: print(row)
This writes two rows to
output.csv: a header and one data row.Python
import csv with open('output.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['City', 'Country']) writer.writerow(['Paris', 'France'])
DictReader reads rows as dictionaries using the header row as keys.Python
import csv with open('people.csv', newline='') as file: reader = csv.DictReader(file) for row in reader: print(row['Name'], row['Age'])
DictWriter writes rows using dictionary keys matching the header fields.Python
import csv with open('people.csv', 'w', newline='') as file: fieldnames = ['Name', 'Age'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'Name': 'Bob', 'Age': 25})
Sample Program
This program first writes two rows of data to sample.csv. Then it reads the file and prints each row as a list.
Python
import csv # Write sample data to CSV with open('sample.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Score']) writer.writerow(['Alice', 85]) writer.writerow(['Bob', 90]) # Read and print the CSV data with open('sample.csv', newline='') as file: reader = csv.reader(file) for row in reader: print(row)
OutputSuccess
Important Notes
CSV files separate values by commas by default, but you can change the separator with the delimiter option.
Always close files or use with to handle files safely.
When reading, all data is read as text (strings). Convert to numbers if needed.
Summary
CSV files store data in rows and columns separated by commas.
Use Python's csv module to read and write CSV files easily.
Use csv.reader for simple lists and csv.DictReader for named columns.