Python – My CSV writer code writes delimiters between characters, not strings

My CSV writer code writes delimiters between characters, not strings… here is a solution to the problem.

My CSV writer code writes delimiters between characters, not strings

I wrote code that writes to a CSV file and reads from another file. I want to write out specific columns from the input file, so I append them to the list and then separate them with commas and add them to the rows, but the characters that the output file shows for individual words are also separated by commas. I just want to separate words, not 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)

The output is as follows:

    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

Although it should be like this :

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

When I make the following modifications

   write.writerow([line])

It displays the complete string in one column of the excel file, which means there is only one column, and I want 6.

Solution

Here’s the problem:

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

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

But you don’t give it a list of columns; You give it a string. That’s what ','.join(r) does: convert the column list to 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. (This is 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)

Related Problems and Solutions