Bird
Raised Fist0
Pythonprogramming~20 mins

Reading and writing CSV data in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
CSV Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Reading CSV with csv.reader
What is the output of this code snippet that reads a CSV string using csv.reader?
Python
import csv
from io import StringIO

csv_data = "name,age\nAlice,30\nBob,25"
file_like = StringIO(csv_data)
reader = csv.reader(file_like)
rows = list(reader)
print(rows)
A['name,age', 'Alice,30', 'Bob,25']
B[{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]
C[['name', 'age'], ['Alice', '30'], ['Bob', '25']]
DSyntaxError
Attempts:
2 left
💡 Hint
csv.reader returns each row as a list of strings.
Predict Output
intermediate
2:00remaining
Writing CSV with csv.DictWriter
What is the output of this code that writes a list of dictionaries to CSV format using csv.DictWriter?
Python
import csv
from io import StringIO

output = StringIO()
fieldnames = ['name', 'age']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'Alice', 'age': 30})
writer.writerow({'name': 'Bob', 'age': 25})
print(output.getvalue())
Aname,age\nAlice,30\nBob,25\n
B['name', 'age']\n['Alice', '30']\n['Bob', '25']
C{'name': 'Alice', 'age': 30}\n{'name': 'Bob', 'age': 25}
DTypeError
Attempts:
2 left
💡 Hint
csv.DictWriter writes CSV rows as strings with headers.
Predict Output
advanced
2:00remaining
Reading CSV with custom delimiter
What is the output of this code that reads CSV data with a semicolon delimiter?
Python
import csv
from io import StringIO

csv_data = "name;age\nAlice;30\nBob;25"
file_like = StringIO(csv_data)
reader = csv.reader(file_like, delimiter=';')
rows = list(reader)
print(rows)
A[['name;age'], ['Alice;30'], ['Bob;25']]
BValueError
C[{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]
D[['name', 'age'], ['Alice', '30'], ['Bob', '25']]
Attempts:
2 left
💡 Hint
Specify the delimiter parameter to split columns correctly.
Predict Output
advanced
2:00remaining
Writing CSV with quoting
What is the output of this code that writes CSV data with quoting for all fields?
Python
import csv
from io import StringIO

output = StringIO()
fieldnames = ['name', 'note']
writer = csv.DictWriter(output, fieldnames=fieldnames, quoting=csv.QUOTE_ALL)
writer.writeheader()
writer.writerow({'name': 'Alice', 'note': 'Hello, world!'})
writer.writerow({'name': 'Bob', 'note': 'Goodbye'})
print(output.getvalue())
Aname,note\nAlice,Hello, world!\nBob,Goodbye\n
B"name","note"\n"Alice","Hello, world!"\n"Bob","Goodbye"\n
C['name', 'note']\n['Alice', 'Hello, world!']\n['Bob', 'Goodbye']
DSyntaxError
Attempts:
2 left
💡 Hint
csv.QUOTE_ALL adds quotes around every field.
🧠 Conceptual
expert
2:00remaining
csv.DictReader behavior without header row
What is the output of this code when reading CSV data without a header row using csv.DictReader?
Python
import csv
from io import StringIO

csv_data = "Alice,30\nBob,25"
file_like = StringIO(csv_data)
reader = csv.DictReader(file_like)
rows = list(reader)
print(rows)
A[{'Alice': 'Bob', '30': '25'}]
BValueError
C[{'fieldnames': None}, {'fieldnames': None}]
D[{'Alice': '30'}, {'Bob': '25'}]
Attempts:
2 left
💡 Hint
csv.DictReader uses the first row as header by default.

Practice

(1/5)
1. What does the Python csv.reader function do when reading a CSV file?
easy
A. It deletes rows from the CSV file.
B. It reads the file and returns each row as a list of strings.
C. It converts CSV data into a dictionary automatically.
D. It writes data to a CSV file.

Solution

  1. Step 1: Understand csv.reader purpose

    The csv.reader reads CSV files and returns each row as a list of strings representing columns.
  2. Step 2: Differentiate from other functions

    Functions like csv.DictReader return dictionaries, and writing functions save data, not read it.
  3. Final Answer:

    It reads the file and returns each row as a list of strings. -> Option B
  4. Quick Check:

    csv.reader returns lists [OK]
Hint: csv.reader reads rows as lists, not dictionaries [OK]
Common Mistakes:
  • Confusing csv.reader with csv.DictReader
  • Thinking csv.reader writes data
  • Assuming it deletes or modifies files
2. Which of the following is the correct way to open a CSV file for writing in Python?
easy
A. open('file.csv', 'w', newline='')
B. open('file.csv', 'r')
C. open('file.csv', 'a', encoding='utf-8')
D. open('file.csv', 'rb')

Solution

  1. Step 1: Identify mode for writing CSV

    To write CSV files, open the file in write mode 'w' and use newline='' to prevent extra blank lines on Windows.
  2. Step 2: Check other options

    'r' is read mode, 'a' is append (valid but not asked), 'rb' is binary read mode (not for writing text CSV).
  3. Final Answer:

    open('file.csv', 'w', newline='') -> Option A
  4. Quick Check:

    Write mode with newline='' [OK]
Hint: Use 'w' mode with newline='' to write CSV files correctly [OK]
Common Mistakes:
  • Forgetting newline='' causes blank lines
  • Using 'r' mode when writing
  • Using binary mode for text CSV
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)
    for row in reader:
        print(row)
medium
A. ['Name', 'Age']\n['Alice', 30]
B. Name,Age\nAlice,30
C. ['Name', 'Age']\n['Alice', '30']
D. Error because of missing encoding

Solution

  1. Step 1: Writing rows with csv.writer

    The code writes two rows: header ['Name', 'Age'] and data ['Alice', 30]. Numbers are converted to strings when written.
  2. Step 2: Reading rows with csv.reader and printing

    Reading returns each row as a list of strings. print(row) shows repr with quotes: ['Name', 'Age'] and ['Alice', '30'].
  3. Final Answer:

    ['Name', 'Age']\n['Alice', '30'] -> Option C
  4. Quick Check:

    csv.writer writes lists, csv.reader reads lists [OK]
Hint: csv.reader returns lists of strings, print shows quotes around all elements [OK]
Common Mistakes:
  • Expecting printed rows as comma strings
  • Confusing string and integer types in output
  • Assuming encoding error without cause
4. Identify the error in this code that reads a CSV file:
import csv
with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
    print(row)
medium
A. Indentation error in the for loop
B. Missing import statement for csv module
C. File opened in wrong mode
D. csv.reader requires newline argument

Solution

  1. Step 1: Check code indentation

    The print statement inside the for loop must be indented to be part of the loop body.
  2. Step 2: Verify other parts

    Import is present, file mode 'r' is correct for reading, and newline argument is not needed for reading.
  3. Final Answer:

    Indentation error in the for loop -> Option A
  4. Quick Check:

    Python requires correct indentation [OK]
Hint: Indent inside loops to avoid syntax errors [OK]
Common Mistakes:
  • Forgetting to indent inside loops
  • Thinking newline is needed for reading
  • Confusing file modes
5. You want to read a CSV file where the first row contains column names, and then write a new CSV file with only rows where the 'Age' column is greater than 25. Which approach is correct?
hard
A. Use csv.reader to read, skip first row manually, filter rows, then write with csv.writer.
B. Use csv.writer to read and write files directly without filtering.
C. Use csv.reader to read all rows, convert 'Age' to int, then write with csv.DictWriter without header.
D. Use csv.DictReader to read rows as dictionaries, filter by 'Age' key, then write with csv.DictWriter including header.

Solution

  1. Step 1: Choose reading method with headers

    csv.DictReader reads CSV rows as dictionaries using the first row as keys, making it easy to filter by column names like 'Age'.
  2. Step 2: Filter and write with headers

    Filter rows where 'Age' > 25, then write using csv.DictWriter with fieldnames to include headers properly.
  3. Final Answer:

    Use csv.DictReader to read rows as dictionaries, filter by 'Age' key, then write with csv.DictWriter including header. -> Option D
  4. Quick Check:

    DictReader + DictWriter for header and filtering [OK]
Hint: Use DictReader/DictWriter for header-based filtering [OK]
Common Mistakes:
  • Skipping header manually instead of using DictReader
  • Writing without headers causing missing columns
  • Using csv.writer without filtering logic