Skip to content
Advertisement

Issue with writing CSV in Python

I am reading and XLSX file. and looping over the rows and colums to remove all the clutter from the excel.

    with open("../Converted/test.csv", "w") as f:
        writer = csv.writer(f)
        writer.writerow(header) # write the header        
               
        for i in range(10, max_row + 1):
            full_data_row = ""
            for j in range(1, max_col + 1):
                cell_obj = sheet_obj.cell(row = i, column = j)
                if cell_obj.value is not None:
                    full_data_row += str(cell_obj.value) + ','

            full_data_row = full_data_row[:-1]
            writer.writerow(full_data_row)

When I print full_data_row it prints the string with , so that is correct. When i check my csv file. I get this as an ouput:

header1,header2,header3 O,p,z,e,t, ,h,o,s,t,e,d,

Advertisement

Answer

csvwriter.writerow() expects an iterable (e.g. a list), and will handle the formatting (placing commas between values) for you. Therefore, it parses your string as a list (of characters), printing commas between every character.

An alternative approach could be:

for i in range(10, max_row + 1):
    full_data_row = []
    for j in range(1, max_col + 1):
        cell_obj = sheet_obj.cell(row = i, column = j)
        if cell_obj.value is not None:
            full_data_row.append(str(cell_obj.value))

    writer.writerow(full_data_row)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement