Python : set delimiter as both comma and space ', '

2k Views Asked by At

I want to append my CSV file with a new row But the new row must be separated by a comma as well as space between them. I can only separate them with either comma or space.

The current file is:

data.csv

1,abc1,xyz1
2,abc2,xyz2
3,abc3,xyz3
4,abc4,xyz4
5,abc5,xyz5

I want it as :

data.csv

1, abc1, xyz1
2, abc2, xyz2
3, abc3, xyz3
4, abc4, xyz4
5, abc5, xyz5

My code for writing CSV:

my_new_row = [6, 'abc6', 'xyz6']
with open('data.csv', 'a', newline='') as filehandle:
    writer = csv.writer(filehandle, delimiter=',')
    writer.writerow(my_new_row)
5

There are 5 best solutions below

0
kamho On BEST ANSWER

The format you want to print is seem like not a stander CSV format. So you can write your own writer to print that string format.

Common Format and MIME Type for Comma-Separated Values (CSV) Files

1
Tabaene Haque On

Not the best solution, but based on your requirement, one solution that I can think off is

import csv
my_new_row = [6, 'abc6', 'xyz6']
with open('data.csv', 'a') as filehandle:
    writer = csv.writer(filehandle, delimiter=',')
    writer.writerow([' ' + str(i) if isinstance(i, str) else i for i in my_new_row])

O/P: 6, abc6, xyz6

Try this and let me know if this help.

0
kendall-johnston On

This certainly isn't very efficient but it does solve your problem, with only the new row containing spaces after the delimiter.

import csv

my_new_row = [6, 'abc6', 'xyz6']
x, y = ',', ', '

with open('data.csv', 'r', newline='') as original_file:
    original_reader = csv.reader(original_file)
    with open('new_file.csv', 'w', newline='') as new_file:
        new_writer = csv.writer(new_file, delimiter=',')
        for line in original_reader:
            new_writer.writerow(line)
        with open('temp_file.csv', 'w+', newline='') as temp_file:
            temp_reader = csv.reader(temp_file)
            temp_writer = csv.writer(temp_file, delimiter=',')
            temp_writer.writerow(my_new_row)
            temp_file.seek(0)
            data = temp_file.read()
            temp_file.seek(0)
            temp_file.write(data.replace(x, y))
            temp_file.seek(0)
            for line in temp_reader:
                new_writer.writerow(line)

The output is all written to the new_file.csv

0
Lalit kumar On

AS CVS file format means "," comma-separated value, I am assuming now you no longer required CSV output file but rather a simple text output file.

Below code would produce your desired output

def readAndWriteFile(read_file_path,write_file_path):
    with open(read_file_path,"r") as fin:
        output = [", ".join(element.split(',')) for element in fin.readlines()]
    print("output:",output)
    
    with open(write_file_path,'w') as fout:
        fout.writelines(output)
0
Subasri sridhar On

Here is a simple workaround :

import csv

class CSV_Translater(object):
    """ Output file-like object that translates characters. """
    def __init__(self, f, old, new):
        self.f = f
        self.old = old
        self.new = new
    def write(self, s):
        self.f.write(s.replace(self.old, self.new))
    def close(self):
        self.f.close()
    def flush(self):
        self.f.flush()

my_new_row = ['6', 'abc6', 'xyz6']


with open('data.csv', "r+") as filehandle:
    reader = csv.reader(filehandle)
    with open('out_test.csv', "w") as opfile:
        translater = CSV_Translater(opfile, ',', ', ')
        writer = csv.writer(translater, delimiter=',')
        for row in reader:
            writer.writerow(row)
        writer.writerow(my_new_row)

Sample File output Screenshots1