Computer Science
How do you change the delimiter of a csv file while writing into it ?
Python File Handling
1 Like
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:
- We open the CSV file for writing using the open() function with mode 'w'.
- We create a CSV writer object csv_writer using csv.writer() and specify the desired delimiter using the delimiter parameter.
- 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.
Answered By
1 Like