-4

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.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130

3 Answers3

2

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
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

Here's another option, maybe the easiest

#!/usr/bin/env python3

Mylist = [1,3,67,43,23,52,7,9,21]
filename = 'outfile.csv'

with open(filename, 'w') as outfile:
    for i in range(0, len(Mylist), 3):
        print('{} {} {}'.format(Mylist[i], Mylist[i+1], Mylist[i+2]))

Output

1 3 67
43 23 52
7 9 21
MightyPork
  • 18,270
  • 10
  • 79
  • 133