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):
What you want to do is read in the data from the file, then split it into individual elements. Once you have it in individual elements you can put them in groups of three and write to your output file.
Something like this should work:
def read_data(file_path):
with open(file_path, 'r') as fh:
elements = fh.read()
data = [element.strip() for element in elements.split(',')]
return data
def group(data):
grouped = [', '.join(data[n:n+3]) for n in range(0, len(data), 3)]
return grouped
def write(data, output):
with open(output, 'w') as fh:
fh.writelines(data)
def main():
data = read('test.csv')
data = group(data)
write(data, 'test2.csv')