CH 5 File Handling CSV Files
CH 5 File Handling CSV Files
CH 5 File Handling CSV Files
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 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.
ANSWERS
1.A) csv
2.B) To write data into a CSV file
3.B) 'w'
4. C) writerow()
5. B) close()
6. B) writerows()
7. D) newline=None
8. D) for loop
9. C) It ensures universal newline support.
10.D) 'x' (exclusive creation mode)
11.B) Text-based
12.D) list()
13. B) writerow()
14. C) The delimiter character separates values within a CSV file.
15. B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
16.A) It requires less memory compared to other modules.
17.A) It prevents empty lines from being written.
18.C) List
19.D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. B) To ensure cross-platform compatibility for newline characters.
2 marks questions
1.The csv module in Python is used to work with CSV (Comma Separated Values) files. It provides
functions to read, write, and manipulate data in CSV format, making it easier to handle tabular data.
2.
Newline handling is crucial when working with CSV files because different operating systems use
different newline characters (such as '\n' for Unix/Linux and '\r\n' for Windows). If newline
handling is not done correctly, it can lead to issues like extra blank lines or improper row parsing.
Using newline='' in the open() function ensures universal newline support, preventing such issues.
3.
writerow(): Writes a single row of data into the CSV file.
writerows(): Writes multiple rows of data into the CSV file. It takes an iterable of rows (e.g., a list
of lists) and writes each row as a separate line in the CSV file.
4.
A CSV file is a text-based file format used to store tabular data. Each line in a CSV file represents a
row, and values within each row are separated by a delimiter character, commonly a comma (','),
although other characters like tabs or semicolons can also be used.
5.
The delimiter character is used to separate values within a CSV file. It signifies where one value
ends and the next one begins within a row. Common delimiter characters include commas (','), tabs
('\t'), semicolons (';'), and pipes ('|'). The choice of delimiter depends on the data and the
requirements of the CSV file.
6.
import csv
data = ['Name', 'Age', 'City']
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data)
7.
import csv
try:
with open('input.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
8.
import csv
import random
data = [['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'San Francisco'],
['Charlie', 28, 'Los Angeles']]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
9
import csv
new_data = [['David', 35, 'Chicago'],
['Emma', 29, 'Houston']]
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerows(new_data)
10.
import csv
def count_rows(csv_file):
try:
with open(csv_file, 'r') as file:
reader = csv.reader(file)
row_count = sum(1 for row in reader)
return row_count
except FileNotFoundError:
return 0
except Exception as e:
print("Error:", e)
return 0
file_path = 'data.csv'
total_rows = count_rows(file_path)
print("Total rows in", file_path, ":", total_rows)
import csv
low_stock_items = []
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
3 MARKS QUESTIONS ANSWERS
1.
import csv
low_stock_items = []
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
2.
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 += float(row[2]) # Assuming Price is in the third column
print('Total revenue:', total_revenue)
3.
import csv
total_salary = 0
with open('employees.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_salary += int(row[2]) # Assuming Salary is in the third column
print('Total salary:', total_salary)
4.
import csv
def write_student_data(file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Grade']) # Write header row
while True:
name = input("Enter student name (or type 'exit' to quit): ")
if name.lower() == 'exit':
break
grade = input("Enter student grade: ")
writer.writerow([name, grade])
except Exception as e:
print("Error:", e)
write_student_data('students.csv')
5.
Delimiter characters in CSV files are used to separate individual fields (data values) within a row.
The most common delimiter character is a comma (,), but other characters like tabs (\t), semicolons
(;), and pipes (|) can also be used.
The significance of delimiter characters when working with the csv module in Python is that they
determine how data is organized and interpreted within a CSV file. When reading a CSV file,
Python uses the specified delimiter character to split each row into individual fields, making it
possible to access and process the data accordingly. Similarly, when writing data to a CSV file, the
delimiter character is used to separate different values within each row. Using the correct delimiter
ensures that the data is correctly formatted and can be read or written without errors.
6.
import csv
# Define the input and output file names
input_file = 'data.csv'
output_file = 'high_scores.csv'
# Open the input and output CSV files
with open(input_file, 'r') as file:
reader = csv.reader(file)
with open(output_file, 'w', newline='') as output_file:
writer = csv.writer(output_file # Write header row to the output file
header = next(reader)
writer.writerow(header)
# Iterate through each row in the input file
for row in reader:
# Check if the value in the second column is greater than 50
if int(row[1]) > 50: # Assuming the second column contains integers
writer.writerow(row)
7.import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)
8.Correct code:
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)
output:
Total inventory cost: 500.0
9.
import csv
student_dict = {}
with open('students.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
name, age, grade = row
student_dict[name] = [int(age), grade]
print(student_dict)
10.
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(row[2]) # Assuming sales amount is in the third column
total_sales += sales_amount
print('Total sales amount:', total_sales)
5 MARKS QUESTIONS ANSWERS
1. import csv
product_values = {}
with open('inventory.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
price = float(row['Price'])
total_value = quantity * price
if product in product_values:
product_values[product] += total_value
else:
product_values[product] = total_value
print("Summary Report - Total Value of Each Product:")
for product, total_value in product_values.items():
print(f"{product}: ${total_value:.2f}")
2.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
3
import csv
product_data = [
{'Name': 'Laptop', 'Quantity': 10, 'Price': 1200},
{'Name': 'Mouse', 'Quantity': 50, 'Price': 20},
{'Name': 'Keyboard', 'Quantity': 20, 'Price': 50}
]
fieldnames = ['Name', 'Quantity', 'Price']
with open('output.csv', 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(product_data)
4.
import csv
product_revenue = {}
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
product = row[1] # Assuming Product is in the second column
revenue = float(row[2]) # Assuming Revenue is in the third column
if product in product_revenue:
product_revenue[product] += revenue
else:
product_revenue[product] = revenue
print("Total Revenue Earned for Each Product:")
for product, total_revenue in product_revenue.items():
print(f"{product}: ${total_revenue:.2f}")
5.
import csv
# Read data from sales.csv
sales_data = {}
with open('sales.csv', 'r') as sales_file:
reader = csv.DictReader(sales_file)
for row in reader:
date = row['Date']
product = row['Product']
revenue = float(row['Revenue'])
if product not in sales_data:
sales_data[product] = {'Date': date, 'Revenue': revenue}
else:
sales_data[product]['Revenue'] += revenue
# Read data from inventory.csv
inventory_data = {}
with open('inventory.csv', 'r') as inventory_file:
reader = csv.DictReader(inventory_file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
inventory_data[product] = quantity