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):
Here's a solution but it's a bit long. Basically I would write all the values in the csv to a list, then remove three value from the list and write to the csv until there's no values left.
import csv
# just an example csv
with open('example.csv', 'w') as csvfile:
# create example csv with a single row of numbers 0-19
spamwriter = csv.writer(csvfile)
spamwriter.writerow([i for i in range(20)])
# open file for reading, append values to list
l = []
with open('example.csv') as csvfile:
# read the example file into a list
reader = csv.reader(csvfile)
for row in reader:
for val in row:
l.append(val)
# write to the original file with 3 values per line
with open('example.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile)
while l:
try:
# write to file 3 values at a time
spamwriter.writerow(l[:3])
l = l[3:]
except:
# add last bit of file, if file doesn't devide evenly by 3
spamwriter.writerow(l)
break
I'd recommend checking out Pandas I find it a lot easier to manipulate csvs with it, but it's not in the standard library.