CSV files store data in a simple table format. Learning to work with them helps you read and save data easily.
Working with CSV files in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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)
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)
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.
Practice
1. What does the Python
csv.reader function do when working with CSV files?easy
Solution
Step 1: Understand the purpose of
Thecsv.readercsv.readerfunction reads CSV files and returns each row as a list of strings representing the columns.Step 2: Differentiate from other CSV functions
Functions like writing or deleting files are not done bycsv.reader. It only reads and parses rows.Final Answer:
Reads the CSV file and returns each row as a list of values -> Option AQuick Check:
csv.readerreads rows as lists [OK]
Hint: Remember: reader reads rows as lists [OK]
Common Mistakes:
- Confusing reader with writer
- Thinking it deletes files
- Assuming it converts formats
2. Which of the following is the correct way to open a CSV file for reading in Python?
easy
Solution
Step 1: Understand file modes in Python
The mode 'r' means open for reading, which is needed to read a CSV file.Step 2: Check other modes
'w' is for writing (overwrites), 'a' is for appending, and 'x' is for creating a new file. None are for reading existing files.Final Answer:
open('data.csv', 'r') -> Option CQuick Check:
Use 'r' mode to read files [OK]
Hint: Use 'r' mode to read files [OK]
Common Mistakes:
- Using 'w' which overwrites file
- Using 'a' which appends data
- Using 'x' which fails if file exists
3. What will be the output of this code snippet?
import csv
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', '30'])
with open('data.csv', 'r') as f:
reader = csv.reader(f)
rows = list(reader)
print(rows)medium
Solution
Step 1: Writing rows with csv.writer
The code writes two rows: header ['Name', 'Age'] and data ['Alice', '30'] as lists.Step 2: Reading rows with csv.reader
Reading back returns a list of lists, each inner list is a row split by commas.Final Answer:
[['Name', 'Age'], ['Alice', '30']] -> Option DQuick Check:
csv.reader returns list of lists [OK]
Hint: csv.reader returns list of lists, not flat list [OK]
Common Mistakes:
- Expecting a flat list instead of list of lists
- Thinking rows are single strings
- Syntax errors from missing newline='' in open
4. Identify the error in this code that reads a CSV file:
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)medium
Solution
Step 1: Check indentation inside the for loop
The print statement must be indented inside the for loop to run for each row.Step 2: Verify other parts
Import is present, file mode 'r' is correct for reading, and csv.reader works with 'with' statement.Final Answer:
Indentation error in the for loop body -> Option BQuick Check:
Indent loop body correctly [OK]
Hint: Indent inside loops to avoid errors [OK]
Common Mistakes:
- Not indenting loop body
- Changing file mode incorrectly
- Thinking csv.reader can't be used with 'with'
5. You have a CSV file with columns 'Name', 'Age', and 'City'. You want to read it and create a dictionary where keys are names and values are ages (as integers). Which code snippet correctly does this?
hard
Solution
Step 1: Use csv.DictReader to access columns by name
DictReader reads rows as dictionaries, so we can use keys like 'Name' and 'Age'.Step 2: Create dictionary with names as keys and ages as integer values
The comprehension usesrow['Name']as key and convertsrow['Age']to int for value.Final Answer:
import csv with open('data.csv', 'r') as f: reader = csv.DictReader(f) result = {row['Name']: int(row['Age']) for row in reader} print(result) -> Option AQuick Check:
DictReader + dict comprehension with int conversion [OK]
Hint: Use DictReader and convert age to int in comprehension [OK]
Common Mistakes:
- Using csv.reader without column names
- Swapping keys and values
- Not converting age to int
