CSV Files Worksheet2
CSV Files Worksheet2
MCQ
1. Which Python module is used to work with CSV files?
A) csv
B) pandas
C) json
D) os
2. What is the purpose of the csv.writer() object in Python?
A) To read data from a CSV file
B) To write data into a CSV file
C) To perform mathematical operations
D) To create directories
3. To open a CSV file for writing, which mode should you use in the open() function?
A) 'r'
B) 'w'
C) 'a'
D) 'rb'
4. Which method is used to write a single row into a CSV file using the csv.writer() object?
A) write()
B) writerows()
C) writerow()
D) row()
5. How do you close a CSV file after you finish working with it in Python?
A) close_file()
B) close()
C) end()
D) stop()
6. Which method is used to write multiple rows into a CSV file using the csv.writer() object?
A) write()
B) writerows()
C) writerow()
D) row()
7. What parameter should be used in the open() function to ensure correct newline handling
when
working with CSV files?
A) newline='ignore'
B) newline=''
C) newline='skip'
D) newline=None
8. To read data from a CSV file in Python, which method of the csv.reader() object is used to
iterate
through each row?
A) readline()
B) next()
C) readrows()
D) for loop
9. What does the newline='' parameter in the open() function ensure when working with CSV
files?
A) It skips writing empty lines.
B) It converts newlines to spaces.
C) It ensures universal newline support.
D) It prevents reading blank rows.
10. Which of the following is NOT a valid mode for opening a CSV file in Python?
A) 'r' (read mode)
B) 'w' (write mode)
C) 'a' (append mode)
D) 'x' (exclusive creation mode)
11. What type of data format is a CSV file?
A) Binary
B) Text-based
C) Image
D) Executable
12. Which method is used to read the entire contents of a CSV file into a list of lists using the
csv.reader() object?
A) read()
B) readline()
C) next()
D) list()
13.When using the csv.writer() object, which method is used to write a list of data into a CSV
file as a
single row?
A) write()
B) writerow()
C) writeall()
D) row()
14,In Python's CSV module, which of the following is true about delimiter characters?
A) The delimiter character cannot be customized.
B) The delimiter character must always be a comma.
C) The delimiter character separates values within a CSV file.
D) The delimiter character is used for comments.
15. How does the csv.writerows() method differ from the csv.writerow() method?
A) writerows() writes a single row, while writerow() writes multiple rows.
B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
C) writerows() converts data to CSV format, while writerow() writes data as-is.
D) writerows() automatically adds headers, while writerow() does not.
16.Which of the following is a benefit of using the csv module in Python for CSV file
operations?
A) It requires less memory compared to other modules.
B) It automatically converts CSV files to Excel format.
C) It provides advanced data visualization features.
D) It supports various data formats other than CSV.
17.What does the newline='' parameter in the open() function prevent when writing to CSV files?
A) It prevents empty lines from being written.
B) It prevents writing data as binary.
C) It prevents newlines from being converted to spaces.
D) It prevents duplicate rows from being written.
18. When using the csv.reader() object to read from a CSV file, what type of data structure is
each row
of data represented as?
A) String
B) Dictionary
C) List
D) Tuple
19. How does the csv.DictReader() class differ from the csv.reader() class in Python?
A) DictReader() reads data as lists, while reader() reads data as dictionaries.
B) DictReader() reads data with column headers, while reader() does not.
C) DictReader() reads data as tuples, while reader() reads data as dictionaries.
D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. What is the purpose of using the newline='' parameter when opening a CSV file in Python?
A) To convert newlines to spaces.
B) To ensure cross-platform compatibility for newline characters.
C) To skip writing empty lines to the CSV file.
D) To automatically add headers to the CSV file.
2 marks questions
1. What is the purpose of using the csv module in Python?
2. Discuss the importance of newline handling when working with CSV files.
3. Differentiate between writerow() and writerows() methods in the csv.writer() object.
4. Describe the data format of a CSV file.
5. Explain the concept of a delimiter character in CSV files.
6. Write a Python code snippet to open a CSV file named "data.csv" in write mode and write a
single
row of data into it using the csv.writer() object.Include the necessary import statement and
ensure
proper closing of the file after writing.
7. Create a Python script that reads data from a CSV file named "input.csv" using the
csv.reader()
object and prints each row of data to the console.Handle any exceptions that may occur during
file
handling.
8. Write a Python program that generates a CSV file named "output.csv" and writes multiple
rows of
data into it using the csv.writer() object.The data can be generated randomly or from predefined
lists.
9. Modify the previous code to append additional rows of data to the "output.csv" file using the
csv.writer() object.
10.Implement a Python function that takes a CSV file path as input and returns the total number
of
rows in the CSV file using the csv.reader() object.
3 marks questions
1. write a Python program that performs the following tasks:
• Opens a CSV file named "inventory.csv" in read mode using the csv.reader() object.
• Iterates through each row in the CSV file.
• Checks if the quantity (second column) of each item is less than 10. If so, appends the item's
name (first column) to a list named low_stock_items.
• Finally, prints the list low_stock_items containing the names of items with low stock.
2. Fill in the blanks in the following code snippet to open a CSV file named "sales.csv" in read
mode
using the csv.reader() object and calculate the total revenue by summing up the values in the
third
column (Price) of each row.
import csv
total_revenue = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_revenue += _______
print('Total revenue:', total_revenue)
3. Given the CSV file "employees.csv":
Name,Department,Salary Alice,HR,50000 Bob,Engineering,60000 Charlie,Sales,45000
Identify and correct any errors in the following Python code snippet, then determine the output of
the
corrected code:
import csv
total_salary = 0
with open('employees.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
total_salary += row[2]
print('Total salary:', total_salary)
4. Write a Python program that opens a CSV file named "students.csv" in write mode using the
csv.writer() object. The program should prompt the user to enter student names and their
respective
grades, and then write this data into the CSV file. Ensure appropriate error handling for incorrect
input.
5. Explain the concept of delimiter characters in CSV files and discuss their significance when
working with the csv module in Python. Provide examples of different delimiter characters and
explain how they affect the organization and interpretation of data within a CSV file.
6. Write a Python program that reads data from a CSV file named "data.csv" using the
csv.reader()
object. For each row, if the value in the second column (index 1) is greater than 50, write that
row
into a new CSV file named "high_scores.csv" using the csv.writer() object.
7. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in
append
mode and add a new row containing the student's name, age, and grade using the csv.writer()
object.
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(_____)
writer._____(student_data)
Output and Error Handling:
8. Given the following CSV file named "inventory.csv":
What will be the output of the following Python program? If there is any error, identify and
correct it.
total_cost = 0
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
quantity = int(row[1])
price = float(row[2])
total_cost += quantity * price
print('Total inventory cost:', total_cost)
9. Write a Python program that reads data from a CSV file named "students.csv" using the
csv.reader()
object. Create a dictionary where the keys are the student names and the values are lists
containing
their age and grade. Print the dictionary.
10. Fill in the blanks in the following code snippet to read data from a CSV file named
"sales.csv"
using the csv.reader() object and calculate the total sales amount. Print the total sales amount.
import csv
total_sales = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
sales_amount = float(_____[2])
total_sales += sales_amount
print('Total sales amount:', total_sales)
5 mark questions
1. Write a Python program that reads data from a CSV file named "inventory.csv" using the
csv.DictReader() class. The CSV file contains columns for "Product", "Quantity", and "Price".
Your program should calculate the total value of each product in inventory (quantity * price) and
print a summary report showing each product's name and total value.
2. Identify and correct the error in the following Python code that attempts to open a CSV file
named
"data.csv" for writing using the csv.writer() object.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'r') as file:
writer = csv.writer(file) writer.writerows(data)
3. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in write
mode and write multiple rows of data into it using the csv.writer() object. The data to be written
includes product information (name, quantity, price) stored in a list of dictionaries.
import csv
product_data = [ {'Name': 'Laptop', 'Quantity': 10, 'Price': 1200}, {'Name': 'Mouse', 'Quantity':
50, 'Price':
20}, {'Name': 'Keyboard', 'Quantity': 20, 'Price': 50} ]
with open('output.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Quantity', 'Price']
writer = csv.DictWriter(file, fieldnames=_____)
writer.writeheader()
writer.writerows(_____)
4. Write a Python program that reads data from a CSV file named "sales.csv" using the
csv.reader()
object. The CSV file contains columns for "Date", "Product", and "Revenue". Your program
should
calculate and print the total revenue earned for each product across all dates.
5. Write a Python program that reads data from two CSV files, "sales.csv" and "inventory.csv",
using
appropriate methods like csv.reader() or csv.DictReader().
The "sales.csv" file contains columns for "Date", "Product", and "Revenue", while the
"inventory.csv" file contains columns for "Product" and "Quantity". Your program should
combine
these datasets to create a new CSV file named "combined_data.csv" that includes the columns
"Date", "Product", "Revenue", and "Available Quantity". Ensure to handle missing or
mismatched
data appropriately.
Case study based questions-4 marks each
1. Imagine you work for a retail company that stores its daily sales data in a CSV file named
"sales_data.csv". Develop a Python script using the csv module to read this file and generate a
daily
sales report. The report should include total sales revenue, the number of items sold, and a
breakdown of sales by product category.
2. You are managing a student gradebook for a school, and the grade data is stored in a CSV file
named "gradebook.csv". Design a Python program using the csv module to read and update
student
grades. Implement functionalities such as adding new grades, calculating average grades for each
subject, and generating individual progress reports.
3. In a warehouse setting, you have an inventory CSV file named "inventory.csv" containing
product
details like name, quantity, and reorder level. Create a Python application using the csv module
to
track inventory levels, identify low-stock items (below reorder level), and generate a restocking
list
with recommended quantities.
4. A company receives customer feedback through an online survey, and the feedback data is
stored in
a CSV file named "feedback_data.csv". Develop a Python script using the csv module to read
and
analyze the feedback. Implement sentiment analysis to categorize feedback as positive, neutral,
or
negative and generate a summary report highlighting key customer sentiments.
5. You are responsible for managing personal finances and have a CSV file named
"expenses.csv"
containing daily expense records. Build a Python application using the csv module to read and
analyze the expense data. Implement functionalities such as calculating total expenses,
categorizing
expenses (e.g., food, transportation), and generating a budget overview with spending trends.
al_exp})