[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

15. Identify the error in the following code.

(a)
import csv
f = open('attendees1.csv')
csv_f = csv.writer(f)

Answer: Explanation of code (a):

  • Code (a) opens the file “attendees1.csv” in read mode ("r") using open().
  • It then creates a CSV writer object using csv.writer(f). However, it doesn’t write anything to the file in the provided code snippet.

While code (a) doesn’t have an error like code (b), it’s worth noting that it’s incomplete and wouldn’t print the contents of the file unless you add code to write rows using the csv_f.writerow() method.

(b)
import csv
f = open('attendees1.csv')
csv_f = csv.reader()
for row in csv_f:
print(row)

Answer: The error in code (b) is: Missing argument for csv.reader()

Corrected code:

Python
import csv

f = open('attendees1.csv')
csv_f = csv.reader(f)  # Provide the file object as an argument

for row in csv_f:
    print(row)

Explanation:

  • The csv.reader() function in Python requires an argument specifying the file object from which to read the CSV data.
  • In the provided code, csv.reader() is called without any arguments, which is incorrect.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment