arrow
arrow
arrow
Which method out of the following is used to write a line of content in a CSV file in a Python program?
Question

Which method out of the following is used to write a line of content in a CSV file in a Python program?

A.

writer

B.

writerow

C.

write

D.

writeline

Correct option is B


The writerow() method is used to write a single row of content to a CSV file in Python. This method is part of the csv module, and it writes a list (or any iterable) as a single row in the CSV file.
Here’s how it works:
import csv
# Open a CSV file in write mode
with open('example.csv', mode='w', newline='') as file:
writer = csv.writer(file)
# Write a row of data
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 25, 'New York'])
Important Key Points:
1. writerow(): This method writes a list of values as a row to the CSV file. Each element of the list becomes a separate column in the row.
2. writer(): This is the method used to create a writer object that can be used to write to a CSV file. It’s not used directly for writing rows.
3. write(): This method is used to write a string to a file, not specifically to write rows in a CSV format.
4. writeline(): This is not a valid method in Python's csv module.
Knowledge Booster:
· Option (a): The writer method is used to create a writer object, not for writing data. The actual method to write rows is writerow().
· Option (c): The write() method is used for writing strings to a file, but not in the context of writing rows in a CSV file. It does not automatically format the data as CSV.
· Option (d): There is no writeline() method in the csv module in Python. The correct method is writerow() for writing a single row.

Free Tests

Free
Must Attempt

CDP Subject Test 01

languageIcon English
  • pdpQsnIcon20 Questions
  • pdpsheetsIcon20 Marks
  • timerIcon20 Mins
languageIcon English
Free
Must Attempt

EVS Subject Test 01

languageIcon English
  • pdpQsnIcon20 Questions
  • pdpsheetsIcon20 Marks
  • timerIcon20 Mins
languageIcon English
Free
Must Attempt

CTET Paper-I PYP (07 July 2024)

languageIcon English
  • pdpQsnIcon150 Questions
  • pdpsheetsIcon150 Marks
  • timerIcon150 Mins
languageIcon English
test-prime-package

Access ‘EMRS PGT’ Mock Tests with

  • 60000+ Mocks and Previous Year Papers
  • Unlimited Re-Attempts
  • Personalised Report Card
  • 500% Refund on Final Selection
  • Largest Community
students-icon
289k+ students have already unlocked exclusive benefits with Test Prime!
Our Plans
Monthsup-arrow