I am reading and XLSX file. and looping over the rows and colums to remove all the clutter from the excel.
JavaScript
x
14
14
1
with open("../Converted/test.csv", "w") as f:
2
writer = csv.writer(f)
3
writer.writerow(header) # write the header
4
5
for i in range(10, max_row + 1):
6
full_data_row = ""
7
for j in range(1, max_col + 1):
8
cell_obj = sheet_obj.cell(row = i, column = j)
9
if cell_obj.value is not None:
10
full_data_row += str(cell_obj.value) + ','
11
12
full_data_row = full_data_row[:-1]
13
writer.writerow(full_data_row)
14
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:
JavaScript
1
9
1
for i in range(10, max_row + 1):
2
full_data_row = []
3
for j in range(1, max_col + 1):
4
cell_obj = sheet_obj.cell(row = i, column = j)
5
if cell_obj.value is not None:
6
full_data_row.append(str(cell_obj.value))
7
8
writer.writerow(full_data_row)
9