CBSE Class 12 Computer Science Question 100 of 145

File Handling — Question 17

Back to all questions
17
Question

Question 17

How do you change the delimiter of a csv file while writing into it ?

Answer

To change the delimiter of a CSV file while writing into it, we can specify the desired delimiter when creating the CSV writer object. In Python, we can achieve this using the csv.writer() function from the csv module. By default, the delimiter is a comma (,), but we can change it to any other character, such as a tab (\t), semicolon (;), or pipe (|).

import csv
with open('output.csv', 'w', newline='') as csvfile:  
    csv_writer = csv.writer(csvfile, delimiter=';') 
    csv_writer.writerow(['Name', 'Age', 'City'])
    csv_writer.writerow(['John', 30, 'New York'])
    csv_writer.writerow(['Alice', 25, 'London'])

In this example:

  1. We open the CSV file for writing using the open() function with mode 'w'.
  2. We create a CSV writer object csv_writer using csv.writer() and specify the desired delimiter using the delimiter parameter.
  3. We then use the writerow() method of the CSV writer object to write rows to the CSV file, with each row separated by the specified delimiter.