Вы можете использовать нарезку списка Python. См. здесь, если вы незнакомы . По сути, вам нужно «скользящее окно» шириной 16 элементов.
Одно решение:
# create list [1 ... 999] ... we will pretend this is your input data
data = range(1, 1000)
def write_data(filename, data, per_line=16):
with open(filename, "w+") as f:
# get number of lines
iterations = (len(data) / per_line) + 1
for i in range(0, iterations):
# 0 on first iteration, 16 on second etc.
start_index = i * per_line
# 16 on first iteration, 32 on second etc.
end_index = (i + 1) * per_line
# iterate over data 16 elements at a time, from start_index to end_index
line = [str(i) for i in data[start_index:end_index]]
# write to file as comma seperated values
f.write(", ".join(line) + " \n")
# call our function, we can specify a third argument if we wish to change amount per line
write_data("output.txt", data)