Python csv: 41 MCQs with answers

All 41 multiple-choice questions from this kit, free and with no sign-up.

Warm-up · 21 questions

Q1. Which of the following is the correct way to open a file for writing with the csv module?

Beginner
A `open('data.csv', 'w', newline='')` B `open('data.csv', 'w')` C `open('data.csv', 'wb')` D `open('data.csv', 'r+')`
Show answer & explanation

`open('data.csv', 'w', newline='')`

The csv module requires `newline=''` to prevent extra blank lines on some platforms. The `'w'` mode is for text writing, and `'wb'` would be for binary, which is not appropriate for csv.

Q2. What does `csv.reader` return when you iterate over it?

Beginner
A A list of strings for each row B A generator of integers C A list of dictionaries D A tuple of column names
Show answer & explanation

A list of strings for each row

`csv.reader` yields each row as a list of strings. It does not automatically convert to dictionaries or numbers.

Q3. Which of the following is a benefit of using `csv.DictReader` over `csv.reader`?

Beginner
A It allows access to columns by name using the header row. B It handles missing values automatically. C It automatically converts data types. D It is faster for large files.
Show answer & explanation

It allows access to columns by name using the header row.

`csv.DictReader` uses the first row as keys, so you can access fields like `row['Name']` instead of using indices. It does not perform type conversion or handle missing values automatically.

Q4. What happens if you try to parse a CSV file with simple string splitting on commas?

Beginner
A It only works on Windows. B It is faster and more reliable than the csv module. C It works fine for all CSV files. D It fails when fields contain commas, quotes, or newlines.
Show answer & explanation

It fails when fields contain commas, quotes, or newlines.

Simple splitting cannot handle quoted fields that contain the delimiter, leading to incorrect parsing. The csv module is designed to handle these cases correctly.

Q5. How do you read a CSV file that uses semicolons as delimiters?

Beginner
A Use `csv.reader(f, delimiter=';')` B Use `csv.reader(f, quotechar=';')` C Use `csv.reader(f, sep=';')` D Use `csv.reader(f, dialect='semicolon')`
Show answer & explanation

Use `csv.reader(f, delimiter=';')`

The `delimiter` parameter specifies the character that separates fields. `quotechar` is for quoting, and there is no built-in 'semicolon' dialect by default.

Q6. What is the purpose of `io.StringIO` when working with the csv module?

Beginner
A To compress CSV files. B To write binary data to a file. C To parse CSV data from a string instead of a file. D To convert strings to numbers.
Show answer & explanation

To parse CSV data from a string instead of a file.

`io.StringIO` creates an in-memory file-like object from a string, which can be passed to `csv.reader` or `csv.writer` when you don't have a physical file.

Q7. When using `csv.DictWriter`, what must you provide to define the column order?

Beginner
A Nothing; it uses the order of the first row. B A list of column names via the `fieldnames` parameter. C A dictionary mapping column names to types. D A string with comma-separated column names.
Show answer & explanation

A list of column names via the `fieldnames` parameter.

`csv.DictWriter` requires a `fieldnames` list to know the order of columns when writing. It uses this list to write the header and to map dictionary keys to columns.

Q8. What is the default quoting style of the csv module?

Beginner
A `QUOTE_ALL` B `QUOTE_MINIMAL` C `QUOTE_NONNUMERIC` D `QUOTE_NONE`
Show answer & explanation

`QUOTE_MINIMAL`

The default is `QUOTE_MINIMAL`, which quotes fields only when necessary (e.g., when they contain the delimiter, quotechar, or newline).

Q9. Which of the following is a common mistake when writing CSV files?

Beginner
A Using `csv.writer` instead of `csv.reader`. B Forgetting to close the file. C Forgetting to use `newline=''` when opening the file. D Using `newline=''` when opening the file.
Show answer & explanation

Forgetting to use `newline=''` when opening the file.

Forgetting `newline=''` can cause extra blank lines in the output on some platforms. The other options are not common mistakes.

Q10. What does the csv module do when a field contains a double quote character?

Beginner
A It removes the quote. B It replaces it with a single quote. C It raises an error. D It escapes it by doubling it.
Show answer & explanation

It escapes it by doubling it.

According to standard CSV rules, internal quotes are escaped by doubling them. For example, `He said "Hi"` becomes `"He said ""Hi"""` when written.

Q11. How can you define a reusable custom CSV format?

Beginner
A By modifying the `csv` module source code. B By using a lambda function. C By using `csv.register_dialect` to create a named dialect. D By subclassing `csv.reader`.
Show answer & explanation

By using `csv.register_dialect` to create a named dialect.

`csv.register_dialect` allows you to define a set of formatting parameters (delimiter, quotechar, etc.) under a name, which you can then pass via the `dialect` parameter to reader or writer.

Q12. What is the output of the following code? ```python import csv from io import StringIO data = "a,b,c\n1,2,3\n" reader = csv.reader(StringIO(data)) for row in reader: print(row) ```

Beginner
A `['a,b,c']` and `['1,2,3']` B `['a', 'b', 'c\n1', '2', '3']` C It raises an error. D `['a', 'b', 'c']` and `['1', '2', '3']`
Show answer & explanation

`['a', 'b', 'c']` and `['1', '2', '3']`

The reader parses each line into a list of strings, splitting on commas. The output is two lists: `['a', 'b', 'c']` and `['1', '2', '3']`.

Q13. Which of the following is true about the data type of fields read by the csv module?

Beginner
A They are bytes objects. B They are automatically converted to integers or floats. C They depend on the file extension. D They are always strings.
Show answer & explanation

They are always strings.

The csv module does not perform type inference; every field is returned as a string. You must convert to numbers explicitly if needed.

Q14. What is the primary advantage of using the csv module over manual string parsing?

Beginner
A It supports binary files. B It automatically detects the delimiter. C It correctly handles quoting and escaping of special characters. D It is faster for large files.
Show answer & explanation

It correctly handles quoting and escaping of special characters.

The csv module implements the full CSV specification, including quoting rules, so it can handle fields with commas, quotes, and newlines correctly, which manual splitting cannot.

Q15. The csv module is part of Python's standard library and requires no installation.

Beginner
A True B False
Show answer & explanation

True

The csv module is included with Python, so you can import it without any extra installation.

Q16. When writing a CSV file, you should open the file in binary mode to avoid blank lines.

Beginner
A True B False
Show answer & explanation

False

You should open the file in text mode with `newline=''`, not binary mode. Binary mode would not work with the csv module's text-based interface.

Q17. What is the purpose of the `newline=''` parameter when opening a file for CSV writing?

Beginner
Show answer & explanation

—

Without it, the file may contain blank lines, which is a common pitfall.

Q18. How do you read a CSV file and print each row as a list of strings?

Beginner
Show answer & explanation

—

This is the basic usage of `csv.reader`.

Q19. What does the `delimiter` parameter do in `csv.reader`?

Beginner
Show answer & explanation

—

This is used for non-standard delimiters.

Q20. Why is it important to convert numeric strings to numbers when processing CSV data?

Beginner
Show answer & explanation

—

The module does not guess types.

Q21. What happens if you forget to use `newline=''` when writing a CSV file?

Beginner
Show answer & explanation

—

This is a common pitfall.

Building up · 13 questions

Q22. What is the difference between `csv.reader` and `csv.DictReader`?

Intermediate
Show answer & explanation

—

DictReader is more convenient when you have a header and want to access fields by name.

Q23. Why should you avoid using simple string splitting to parse CSV files?

Intermediate
Show answer & explanation

—

This is a common mistake that leads to data corruption.

Q24. How can you parse CSV data that is stored in a string variable?

Intermediate
Show answer & explanation

—

This allows you to use the csv module without a physical file.

Q25. How do you write a header row and data rows using `csv.writer`?

Intermediate
Show answer & explanation

—

`writerow()` takes an iterable of values.

Q26. What is a dialect in the csv module?

Intermediate
Show answer & explanation

—

Dialects allow you to handle different CSV formats consistently.

Q27. What is the default quoting style of the csv module and when does it quote fields?

Intermediate
Show answer & explanation

—

This keeps the output compact while ensuring correctness.

Q28. What is the purpose of `csv.DictWriter` and what parameter is required?

Intermediate
Show answer & explanation

—

It maps dictionary keys to columns.

Q29. How can you read a TSV (tab-separated values) file using the csv module?

Intermediate
Show answer & explanation

—

TSV is a common variation of CSV.

Q30. Consider the following code snippet that reads a CSV file and prints each row: ```python import csv with open('data.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) ``` What is the data type of each `row` variable?

Intermediate
A A string containing the entire line B A tuple of strings, one for each field C A list of strings, one for each field D A dictionary mapping column names to values
Show answer & explanation

A list of strings, one for each field

`csv.reader` returns an iterator that yields each row as a list of strings. Each element corresponds to a field in the CSV row, and all values are strings because the csv module does not perform type conversion.

Q31. You are writing a CSV file using `csv.writer`. Which of the following file-opening modes is correct to avoid blank lines in the output?

Intermediate
A `open('output.csv', 'w')` B `open('output.csv', 'w', newline='')` C `open('output.csv', 'r', newline='')` D `open('output.csv', 'wb')`
Show answer & explanation

`open('output.csv', 'w', newline='')`

When writing CSV files, you must open the file with `newline=''` to prevent the csv module from adding extra carriage returns, which cause blank lines on some platforms (especially Windows). Opening in binary mode (`'wb'`) is not required and can cause issues with text encoding.

Q32. Given the following CSV data stored in a string: ```python csv_data = "name,age\nAlice,30\nBob,25" ``` Which code correctly parses this data into rows using the csv module?

Intermediate
A `rows = csv.reader(io.StringIO(csv_data))` B `rows = csv.reader(csv_data)` C `rows = csv.reader(csv_data.split('\n'))` D `rows = csv.reader(StringIO(csv_data))`
Show answer & explanation

`rows = csv.reader(StringIO(csv_data))`

The csv module expects a file-like object, not a plain string. `io.StringIO` wraps the string in a file-like object, making it acceptable. The correct import is `from io import StringIO`, so `csv.reader(StringIO(csv_data))` is correct. The other options either pass the raw string (which is not iterable in the expected…

Q33. You have a CSV file that uses semicolons (`;`) as delimiters and also contains fields with embedded semicolons. Which approach correctly reads this file?

Intermediate
A Use `csv.reader(f, delimiter=';')` and rely on the module to handle quoting. B Use `csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONE)` to disable quoting. C Use `csv.reader(f)` and then replace semicolons with commas in each line. D Use `csv.reader(f, quotechar=';')` to treat semicolons as quotes.
Show answer & explanation

Use `csv.reader(f, delimiter=';')` and rely on the module to handle quoting.

The `delimiter` parameter tells the csv module to use semicolons as field separators. The module still respects quoting rules, so fields containing semicolons will be quoted and parsed correctly. Simply replacing semicolons with commas would break quoted fields. Setting `quotechar=';'` would misinterpret semicolons as…

Q34. When using `csv.DictWriter`, what happens if you try to write a row that contains a key not specified in the `fieldnames` parameter?

Intermediate
A The row is skipped entirely. B The extra key is added to the output as a new column. C A `ValueError` is raised. D The extra key is silently ignored.
Show answer & explanation

A `ValueError` is raised.

`csv.DictWriter` uses the `fieldnames` list to determine the order and which keys to write. If a dictionary passed to `writerow` contains a key not in `fieldnames`, Python raises a `ValueError` to alert you to the inconsistency. This prevents silent data loss or unexpected columns.

Topper level · 7 questions

Q35. How does the csv module handle fields that contain double quotes?

Advanced
Show answer & explanation

—

This ensures the quotes are preserved and the field is correctly parsed.

Q36. How do you create a reusable custom dialect for a legacy system that uses semicolons and a specific quote character?

Advanced
Show answer & explanation

—

This allows you to reuse the format without repeating parameters.

Q37. You are writing a function that reads a CSV file with a header row and returns a dictionary mapping each column name to a list of values, converting numeric-looking values to floats. Which implementation correctly handles quoted fields and type conversion?

Advanced
A ```python def read_csv_numeric(path): with open(path) as f: reader = csv.DictReader(f) result = {} for row in reader: for key, val in row.items(): result.setdefault(key, []).append(float(val)) return result ``` B ```python def read_csv_numeric(path): with open(path, newline='') as f: reader = csv.DictReader(f) result = {} for row in reader: for key, val in row.items(): if val.isdigit(): result.setdefault(key, []).append(float(val)) else: result.setdefault(key, []).append(val) return result ``` C ```python def read_csv_numeric(path): with open(path, newline='') as f: reader = csv.reader(f) header = next(reader) result = {key: [] for key in header} for row in reader: for key, val in zip(header, row): result[key].append(float(val)) return result ``` D ```python def read_csv_numeric(path): with open(path, newline='') as f: reader = csv.DictReader(f) result = {} for row in reader: for key, val in row.items(): try: result.setdefault(key, []).append(float(val)) except ValueError: result.setdefault(key, []).append(val) return result ```
Show answer & explanation

```python def read_csv_numeric(path): with open(path, newline='') as f: reader = csv.DictReader(f) result = {} for row in reader: for key, val in row.items(): try: result.setdefault(key, []).append(float(val)) except ValueError: result.setdefault(key, []).append(val) return result ```

The correct implementation uses `newline=''` to avoid newline translation issues, `csv.DictReader` to handle headers and quoting, and a try/except to convert numeric strings to floats while preserving non-numeric values. Option B fails because it omits `newline=''` and crashes on non-numeric fields. Option C uses `csv.…

Q38. You have a CSV file where some fields contain newlines and quotes. You need to read it and count the number of records where the 'status' column equals 'active'. Which code correctly handles this?

Advanced
A ```python import csv count = 0 with open('data.csv', newline='') as f: reader = csv.reader(f) header = next(reader) for row in reader: if row[header.index('status')] == 'active': count += 1 print(count) ``` B ```python import csv count = 0 with open('data.csv', newline='') as f: reader = csv.DictReader(f) for row in reader: if row.get('status') == 'active': count += 1 print(count) ``` C ```python import csv count = 0 with open('data.csv', newline='') as f: reader = csv.DictReader(f) for row in reader: if row['status'] == 'active': count += 1 print(count) ``` D ```python import csv count = 0 with open('data.csv', 'r') as f: for line in f: fields = line.strip().split(',') if fields[2] == 'active': count += 1 print(count) ```
Show answer & explanation

```python import csv count = 0 with open('data.csv', newline='') as f: reader = csv.DictReader(f) for row in reader: if row['status'] == 'active': count += 1 print(count) ```

The correct option uses `csv.DictReader` with `newline=''`, which properly handles quoted newlines and quotes, and accesses the 'status' column by name. Option B fails because manual splitting breaks on embedded commas and newlines. Option C uses `csv.reader` and `header.index('status')` which is correct but less direc…

Q39. You are given a CSV string with a custom dialect: fields are separated by `|`, quoted with `'`, and lines end with `\r\n`. You need to parse it and write a new CSV with standard comma delimiters and double quotes. Which code correctly handles this transformation?

Advanced
A ```python import csv from io import StringIO data = "'Alice'|30|'New York'\r\n'Bob'|25|'LA'\r\n" reader = csv.reader(StringIO(data), delimiter='|', quotechar='"') with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) for row in reader: writer.writerow(row) ``` B ```python import csv from io import StringIO data = "'Alice'|30|'New York'\r\n'Bob'|25|'LA'\r\n" reader = csv.reader(StringIO(data), delimiter='|') with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) for row in reader: writer.writerow(row) ``` C ```python import csv from io import StringIO data = "'Alice'|30|'New York'\r\n'Bob'|25|'LA'\r\n" reader = csv.reader(StringIO(data), delimiter='|', quotechar="'") with open('output.csv', 'w') as f: writer = csv.writer(f) for row in reader: writer.writerow(row) ``` D ```python import csv from io import StringIO data = "'Alice'|30|'New York'\r\n'Bob'|25|'LA'\r\n" reader = csv.reader(StringIO(data), delimiter='|', quotechar="'") with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) for row in reader: writer.writerow(row) ```
Show answer & explanation

```python import csv from io import StringIO data = "'Alice'|30|'New York'\r\n'Bob'|25|'LA'\r\n" reader = csv.reader(StringIO(data), delimiter='|', quotechar="'") with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) for row in reader: writer.writerow(row) ```

The correct option specifies both `delimiter='|'` and `quotechar="'"` to match the custom dialect, and uses `newline=''` when opening the output file to prevent blank lines. Option B omits the quotechar, so it will not correctly handle fields that contain the quote character. Option C uses the wrong quotechar (double q…

Q40. You have a CSV file with a header row and you want to write a new CSV file that includes only rows where the 'age' column is greater than 30, and you want to add a new column 'age_group' with values '30-40' or '40+' based on the age. Which code correctly performs this transformation?

Advanced
A ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['age_group'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: age = int(row['age']) if age > 30: row['age_group'] = '30-40' if age <= 40 else '40+' writer.writerow(row) ``` B ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['age_group'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: age = int(row['age']) if age > 30: row['age_group'] = '30-40' if age <= 40 else '40+' writer.writerow(row) ``` C ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['age_group'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: age = int(row['age']) if age > 30: row['age_group'] = '30-40' if age <= 40 else '40+' writer.writerow(row) ``` D ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['age_group'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: if int(row['age']) > 30: row['age_group'] = '30-40' if int(row['age']) <= 40 else '40+' writer.writerow(row) ```
Show answer & explanation

```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames + ['age_group'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: age = int(row['age']) if age > 30: row['age_group'] = '30-40' if age <= 40 else '40+' writer.writerow(row) ```

The correct option correctly reads the input with `newline=''`, adds the new fieldname, writes the header, and for each row with age > 30, assigns the age_group based on the age and writes the row. Option B is identical to A except it calls `int(row['age'])` twice, which is inefficient but functionally correct; however…

Q41. You are writing a script that reads a CSV file with a header row and writes a new CSV file with the same data but with all string values stripped of leading/trailing whitespace. Which code correctly handles this, including fields that contain commas and quotes?

Advanced
A ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) for row in reader: stripped = [cell.strip() for cell in row] writer.writerow(stripped) ``` B ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames) writer.writeheader() for row in reader: for key, value in row.items(): row[key] = value.strip() writer.writerow(row) ``` C ```python import csv with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: for key in fieldnames: row[key] = row[key].strip() writer.writerow(row) ``` D ```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: for key in fieldnames: row[key] = row[key].strip() writer.writerow(row) ```
Show answer & explanation

```python import csv with open('input.csv', newline='') as infile, open('output.csv', 'w', newline='') as outfile: reader = csv.DictReader(infile) fieldnames = reader.fieldnames writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in reader: for key in fieldnames: row[key] = row[key].strip() writer.writerow(row) ```

The correct option uses `newline=''` for both files, `csv.DictReader` to handle headers and quoting, and strips each field. Option B omits `newline=''`, which can cause blank lines in the output. Option C uses `csv.reader` and `csv.writer`, which works but does not preserve the header row as a dictionary; it also write…

Make your own

Your notes can be a kit like these

Every kit here was made from real study material. Point Veda at a chapter, a PDF, a photo or a link and get notes, flashcards, practice MCQs, games and a scored test — free, in 42 languages.

  • Chapter notes
  • Flashcards
  • Practice MCQs
  • Scored tests
  • Exam prep

Get Veda free See what students get

Free to start · No ads · Works in 42 languages