jason adams
jason adams

Reputation: 565

replacing all but first commas with blank value

I have a CSV in this format:

A, Hello, my name is John, how are you?
B, Hello John, I'm doing well, thanks!

Right now, the CSV shows four values for the first and second entry since they are both delimited by commas. My goal is to have the CSV show two values for each entry like so:

A, Hello my name is John how are you?
B, Hello John I'm doing well thanks!

I tried the replace function but that converts every single comma into a space. I was wondering if there was such thing that I could skip the first comma and have every comma (after the first one) be replaced by "". Here's what I have so far:

fin = open ('example.csv', 'r+')
fout = open ('newExample.csv', 'w')
reader = csv.reader(fin)
for line in reader:

    for i in range(1, len(line)):
        line[i].replace(',', ''); 
        fout.write(line);    

fin.close()
fout.close()

I don't mind if the solution doesn't follow the below code, whichever is fine, as long as it produces the desired output

Thanks in advance!

Upvotes: 0

Views: 99

Answers (4)

AChampion
AChampion

Reputation: 30258

Given you have used CSV to already split the fields then you can join the first field separate by a ',' with the remaining fields, like:

from io import StringIO
fin = StringIO("""A, Hello, my name is John, how are you?
B, Hello John, I'm doing well, thanks!""")

import csv
reader = csv.reader(fin)
for line in reader:
    print(','.join([line[0], "".join(line[1:])]))

Output:

A, Hello my name is John how are you?
B, Hello John I'm doing well thanks!

Upvotes: 2

Alexander
Alexander

Reputation: 109526

This uses a generator instead of list comprehension. It splits the line into the first section (including the first comma) and then the rest of the line. Depending on your needs, you may need to trim the second portion to remove the extra space.

fin = open('example.csv', 'r+')
reader = csv.reader(fin)
open('newExample2.csv', 'w')

with fout:
    (fout.write(line[:line.find(',') + 1] 
                + line[line.find(','):].replace(',', "")) 
     for line in reader)

fin.close()

Upvotes: 0

Alan He
Alan He

Reputation: 1

Check the index of the first comma, then use a loop to replace, starting from index+1

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

>>> line = 'A, Hello, my name is John, how are you?'
>>> head, tail = line.split(',', 1)
>>> head
'A'

>>> tail
'Hello, my name is John, how are you?'

>>> tail.replace(',', ' ')
'Hello my name is John how are you?'

>>> ','.join([head, tail.replace(',', ' ')]))
'A, Hello my name is John how are you?'

Upvotes: 1

Related Questions