如何将新列写入CSV文件

时间:2015-01-11 18:38:18

标签: python csv

如何在写入CSV文件时创建新列?例如,我有一个数据列表:

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

我想在每三个值之后开始一个新行,所以输出看起来如下,每个数字在一个单独的单元格中并排列成三列(3x3网格):

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

我知道转义函数\n用于启动一个新行,但我该如何开始新列呢?我更喜欢只使用BASIC Python读/写函数,而不是导入的csv模块。这似乎是一件相当容易的事情,但我无法弄明白。

3 个答案:

答案 0 :(得分:2)

不要重新发明轮子。您split up your list into evenly sized chunks,然后使用csv module生成输出:

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])

即使没有模块,您也可以使用str.join()轻松加入列,但必须先将所有值显式映射到字符串:

with open(filename, 'w') as outfile:
    for i in xrange(0, len(Mylist), 3):
        outfile.write(' '.join(map(str, Mylist[i:i + 3])) + '\n')

如果您需要专门填充您的号码以适合2个字符宽的列,请在列表理解中添加format()来电:

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')

'<2'宽度说明符左对齐您的数字与空格。

演示第一个和最后一个选项:

>>> 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

答案 1 :(得分:0)

尝试这样:

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')

输出:

1 3 67
43 23 52
7 9 21

答案 2 :(得分:0)

这是另一种选择,也许是最简单的

#!/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]))

输出

1 3 67
43 23 52
7 9 21