pythoncsvfile-iooutputwriter

My CSV writer code writes separators between characters and not strings


I have written code which writes to a CSV file, reading from another file. I want to write out particular columns from the input file, so I append them to a list, then separate them by a comma and add them to the row, but the output file shows that the individual words' characters are also separated by commas. I only want words to be separated, not the characters.

import csv
def csv_reader(file,path):
    with open(path, 'w') as f1, open(file, 'r') as f2:
        write = csv.writer(f1, delimiter=',')
        read  = csv.reader((line.replace('\0','') for line in f2), delimiter="\t")
        i=1
        for row in read:
            if(len(row)==0):
                continue
            if(row[3]=="Trade"):
                continue
            else:
                if(row[6]==""):
                    r = [row[0],row[0],'A',row[8],row[9],row[0]]
                    line = ','.join(r)
                    print(line)
                    write.writerow(line)
                else:
                    r = [row[0],row[0],'B',row[6],row[7],row[0]]
                    line = ','.join(r)
                    print(line)
                    write.writerow(line)
if __name__ == "__main__":
    path = "sales.csv"
    csv_path = "FlowEdge-TRTH-Time_Sales.csv"
    csv_reader(csv_path,path)

This shows output like:

    0,7,0,0,4,5,0,0,0,0,C,8,.,H,K,",",0,7,0,0,4,5,0,0,0,0,C,8,.,H,K,",",B,",",5,.,7,",",4,",",0,7,0,0,4,5,0,0,0,0,C,8,.,H,K

while it should be like:

    0700450000C8.HK,0700450000C8.HK,B,5.7,4,0700450000C8.HK

when I do the following modification

   write.writerow([line])

It shows the complete string in one column of excel file meaning there is only one column while I want 6 columns.


Solution

  • The problem is here:

    line=','.join(r)
    print(line)
    write.writerow(line)
    

    The writerow method wants a list of columns. It will add the commas between the columns (and quote or escape anything that needs it, etc.).

    But you're not giving it a list of columns; you're giving it a single string. That's what ','.join(r) does: turns a list of columns into a single comma-separated string.

    When you give writerow a string, instead of a list of strings, it treats the string as a sequence of characters. (That's not specific to csv; in Python, a string is a sequence of characters.) So it treats each character as a column, and adds commas between them.

    Just do this:

    write.writerow(r)