Alex
Alex

Reputation: 199

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=',').

Upvotes: 4

Views: 6708

Answers (2)

nocibambi
nocibambi

Reputation: 2421

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.

Upvotes: 3

Lumen
Lumen

Reputation: 51

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)

Upvotes: 2

Related Questions