Don't reinvent the wheel. You split up your list into evenly sized chunks, then use the csv
module to produce your output:
import csv
with open(filename, 'wb') as outfile:
writer = csv.writer(outfile, delimiter=' ')
for i in xrange(0, len(Mylist), 3):
writer.writerow(Mylist[i:i + 3])
Even without the module, you can trivially join your columns using str.join()
, but you have to explicitly map all values to strings first:
with open(filename, 'w') as outfile:
for i in xrange(0, len(Mylist), 3):
outfile.write(' '.join(map(str, Mylist[i:i + 3])) + '\n')
If you need to specifically pad your numbers to fit in columns 2 characters wide, add a format()
call in a list comprehension:
with open(filename, 'w') as outfile:
for i in xrange(0, len(Mylist), 3):
outfile.write(' '.join([format(d, '<2d') for d in Mylist[i:i + 3]]) + '\n')
The '<2'
width specifier left-aligns your numbers with whitespace.
Demo of the first and last options:
>>> import csv
>>> from io import BytesIO
>>> Mylist = [1,3,67,43,23,52,7,9,21]
>>> demo = BytesIO()
>>> writer = csv.writer(demo, delimiter=' ')
>>> for i in xrange(0, len(Mylist), 3):
... writer.writerow(Mylist[i:i + 3])
...
8L
10L
8L
>>> print demo.getvalue()
1 3 67
43 23 52
7 9 21
>>> demo = BytesIO()
>>> for i in xrange(0, len(Mylist), 3):
... demo.write(' '.join([format(d, '<2d') for d in Mylist[i:i + 3]]) + '\n')
...
9L
9L
9L
>>> print demo.getvalue()
1 3 67
43 23 52
7 9 21