0

How I can convert csv data that contain space into comma?

My code

import csv
from pprint import pprint

with open('flare.csv', 'rb') as f:
    reader = str(csv.reader(f))

    for row in reader.splitlines():
        print row

Data

value,id
1 aah
1 aan
3 acc
4 account
1 accounts
1 action
6 ada
3 ade
1 adik
2 admin

Target output

value,id
1,aah
1,aan
3,acc
4,account
1,accounts
1,action
6,ada
3,ade
1,adik
2,admin
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308

3 Answers3

3

Use csv to write your columns as well, just change the delimiter:

import csv

with open('flare.csv', 'rb') as f_in, open("out_flare.csv", "wb") as f_out:
    reader = csv.reader(f_in, delimiter=" ")
    writer = csv.writer(f_out, delimiter=",")
    writer.writerows(reader)

This will make it safe compared to blindly replacing characters as in certain situations your CSV entries will need quotes added around them.

zwer
  • 24,943
  • 3
  • 48
  • 66
  • ooops! you are right; apart from naming my answer is exactly the same as yours and mine came in later... sorry! (i assume you were joking about the carbon-copy..) +1 – hiro protagonist Jun 15 '17 at 20:07
  • @hiroprotagonist - 'twas a joke ;) ... btw. to add something useful, one should always use binary modes when reading/writing CSVs so that the underlying OS doesn't disturb the new lines. That was the only difference between our answers :) – zwer Jun 15 '17 at 20:09
2

You can specify delimiter=' ' to the reader function.

reader = csv.reader(f, delimiter=' ')

It is described here https://docs.python.org/2/library/csv.html#csv-fmt-params

John
  • 21
  • 4
0

Going one line at a time here what you would want to do is:

line = line.split(" ")
line = line.join(",")

Then print back out this line and it should solve your issue. The first part splits apart the line by spaces into a list and the second part then joins the pieces of the list back together into a string with your desired comma.

JoshKopen
  • 940
  • 1
  • 8
  • 22