Question: How to create new columns when writing to a CSV file? For example, I have a list of data:

```
Mylist = [1,3,67,43,23,52,7,9,21]

```

I would like to start a new line after every third value, so the output would look as follows, with each number in a separate cell and arranged into three columns (a 3x3 grid):

```
1  3  67\n
43 23 52\n
7  9  21\n

```

I know that the escape function `\n` is used to start a new line, but how would I go about starting a new column? I would prefer to use only BASIC Python read/write functions, not the imported csv module. This seems like it would be a fairly easy thing to do, but I can't figure it out.

Answer: 
Don't reinvent the wheel. You [split up your list into evenly sized chunks](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python), then use the [`csv` module](https://docs.python.org/2/library/csv.html) 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

```
try like this:

```
Mylist = [1,3,67,43,23,52,7,9,21]
with open('outfile', 'w') as f
    for i in range(len(Mylist)):
        if (i+1)%3 == 0:
            f.write(" ".join(map(str, Mylist[i-2:i+1])) + '\n')

```

output:

```
1 3 67
43 23 52
7 9 21

```