Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting delimiter from semicolon to comma in a CSV?

I have a simple scenario where I am changing the delimiter in a CSV from ; (semicolon) to , (comma). Below is the code

Code:

import csv
semicolonin = csv.reader(r"C:\pyscripts\1.csv", delimiter=';')
commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',')
for row in semicolonin:
    commaout.writerow(row)

But I receive an error. Am I missing something?

TypeError: argument 1 must have a "write" method

while executing line commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',').

like image 517
Alex Avatar asked Oct 18 '25 18:10

Alex


2 Answers

Instead of rewriting your whole CSV file, you can use pandas library.

import pandas as pd

f = pd.read_csv("C:\pyscripts\1.csv")
f.to_csv("C:\pyscripts\1.csv", sep=";")

As you can see, it allows you to read CSV file and choose your separator with the sep='<your_separator>' option, will it be a comma, a semi-colon or the separator of your choosing.

like image 108
nocibambi Avatar answered Oct 20 '25 07:10

nocibambi


You have to provide a file object to the writer method, like so:

import csv
with open(r"C:\pyscripts\1.csv") as in_file, open(r"C:\pyscripts\1.csv", 'w') as out_file:
    semicolonin = csv.reader(in_file, delimiter=';')
    commaout = csv.writer(out_file, delimiter=',')
    for row in semicolonin:
        commaout.writerow(row)
like image 45
Lumen Avatar answered Oct 20 '25 06:10

Lumen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!