I want to create a new CSV file with 3 items per row. My source file looks like (there are no new lines / line breaks):
You mentioned:
My source file looks like (there are no new lines / line breaks):
12123, 1324, 232324, 243443, 234, 2345 2334, 2445, 22355, 222234, 2345
So this reads one long row of a CSV, then writes it as groups of three per line:
import csv
with open('test.csv',newline='') as f:
reader = csv.reader(f)
line = next(reader) # Read the one long line
with open('test2.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for i in range(0,len(line),3): # step by threes.
writer.writerow(line[i:i+3])
Note that correct use of the csv
module requires the files to be opened with newline=''
in Python 3 ('rb' or 'wb' in Python 2).