All 40 questions, laddered from warm-up to topper-level, each with its answer and the reasoning behind it.
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+')`
Answers and explanations are in the Veda app.
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
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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')`
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
Q8.
What is the default quoting style of the csv module?
Beginner
A
`QUOTE_ALL`
B
`QUOTE_MINIMAL`
C
`QUOTE_NONNUMERIC`
D
`QUOTE_NONE`
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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`.
Answers and explanations are in the Veda app.
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']`
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
Q15.
The csv module is part of Python's standard library and requires no installation.
Beginner
Answers and explanations are in the Veda app.
Q16.
When writing a CSV file, you should open the file in binary mode to avoid blank lines.
Beginner
Answers and explanations are in the Veda app.
Q17.
What is the purpose of the `newline=''` parameter when opening a file for CSV writing?
Beginner
Answers and explanations are in the Veda app.
Q18.
How do you read a CSV file and print each row as a list of strings?
Beginner
Answers and explanations are in the Veda app.
Q19.
What does the `delimiter` parameter do in `csv.reader`?
Beginner
Answers and explanations are in the Veda app.
Q20.
Why is it important to convert numeric strings to numbers when processing CSV data?
Beginner
Answers and explanations are in the Veda app.
Q21.
What happens if you forget to use `newline=''` when writing a CSV file?
Beginner
Answers and explanations are in the Veda app.
Building up
· 13 questions
Q22.
What is the difference between `csv.reader` and `csv.DictReader`?
Intermediate
Answers and explanations are in the Veda app.
Q23.
Why should you avoid using simple string splitting to parse CSV files?
Intermediate
Answers and explanations are in the Veda app.
Q24.
How can you parse CSV data that is stored in a string variable?
Intermediate
Answers and explanations are in the Veda app.
Q25.
How do you write a header row and data rows using `csv.writer`?
Intermediate
Answers and explanations are in the Veda app.
Q26.
What is a dialect in the csv module?
Intermediate
Answers and explanations are in the Veda app.
Q27.
What is the default quoting style of the csv module and when does it quote fields?
Intermediate
Answers and explanations are in the Veda app.
Q28.
What is the purpose of `csv.DictWriter` and what parameter is required?
Intermediate
Answers and explanations are in the Veda app.
Q29.
How can you read a TSV (tab-separated values) file using the csv module?
Intermediate
Answers and explanations are in the Veda app.
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
Answers and explanations are in the Veda app.
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')`
Answers and explanations are in the Veda app.
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))`
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
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.
Answers and explanations are in the Veda app.
Topper level
· 6 questions
Q35.
How does the csv module handle fields that contain double quotes?
Advanced
Answers and explanations are in the Veda app.
Q36.
How do you create a reusable custom dialect for a legacy system that uses semicolons and a specific quote character?
Advanced
Answers and explanations are in the Veda app.
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
```
Answers and explanations are in the Veda app.
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)
```
Answers and explanations are in the Veda app.
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)
```
Answers and explanations are in the Veda app.
Q40.
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)
```
Answers and explanations are in the Veda app.