将多个空白字段写入csv python

时间:2015-06-17 14:01:14

标签: python list csv

我尝试将大量CSV导入到数据库表中。

我的导入模板要求设置一组列。如果我的输入数据只有一些所需的列(在我的情况下只有3个),我想将它们放在各自的列中,并将不满意的列留空。

例如,列表List1Column将进入" List1Column"我的模板等等。由于此输入数据不包含其他列的数据,因此' OtherColumn' OtherColumn2'等等,我只是想让它们变空。由于我已将输入数据编译成列表(每个都有效地保存了一列数据),因此我将它们压缩到我想要的模板中。

对于空列,我必须在我的zip迭代中为每个模板empty,empty,empty,empty,empty,empty提供一个空列表。有一个更好的方法吗?我可以说“空”5次'而不是empty,empty,empty,empty,empty,empty

我的输出是相同的两种方式,我只知道我的方法是不好的做法,并希望清理我的代码。我提供了带有代码和输出的示例csv输入。

输入数据

$ cat testcsv.csv  

numbers,AthruZ,LthruN  
1,a,l  
2,b,m  
3,z,n  

代码

import csv
from itertools import izip

huckFin = open('testcsv.csv','rb')
huckCin = csv.reader(huckFin, delimiter=',', quoting=csv.QUOTE_NONE  )
csvdata = [row for row in huckCin]

List1Column = [row[0] for row in csvdata]
List2Column = [row[1] for row in csvdata]
List3Column = [row[2] for row in csvdata]

empty = ['' for row in csvdata]

with open('file.csv', 'wb') as fout:
    csvout = csv.writer(fout, delimiter = ',',
    lineterminator = '\n',
    quotechar = '"'
    )

# My template
csvout.writerow(["List1Column",
                 "OtherColumn",
                 "OtherColumn2",
                 "OtherColumn3",
                 "OtherColumn4",
                 "OtherColumn5",
                 "OtherColumn6",
                 "List2Column",
                 "List3Column"])

csvout.writerows(izip(List1Column,
                      empty,
                      empty,
                      empty,  # Is there a way
                      empty,  # to avoid this list
                      empty,  # of empty columns?
                      empty,
                      List2Column,
                      List3Column))

输出

List1Column,OtherColumn,OtherColumn2,OtherColumn3,OtherColumn4,OtherColumn5,OtherColumn6,List2Column,List3Column  
numbers,,,,,,,AthruZ,LthruN  
1,,,,,,,a,l  
2,,,,,,,b,m  
3,,,,,,,z,n  

另外,我想跳过标题行。在Perl中我会使用:

next if $.==1  
在循环遍历文件之前,

给定标题是第一行。我假设在Python中有一个等价物。我的输出中还有一个额外的新行......我自然会在perl中去:

chomp($output) if eof

我还假设有一个python等同于它。 $output是我的csvout对象。

如果有人对如何以不同方式或更有效率的方式提出更好的建议,请告诉我。

6 个答案:

答案 0 :(得分:3)

尝试print str(empty) * 5

乘法,因为它预期它只适用于字符串。

答案 1 :(得分:0)

您可以使用简单的while

执行此操作
empty = []
i = 0
while i < 5:
    print empty
    i = i + 1

答案 2 :(得分:0)

使用for循环。

for _ in range(5):
    print listname,

请注意,在print命令中使用逗号意味着它们都在同一行(您似乎想要)。

答案 3 :(得分:0)

>>> from __future__ import print_function
>>> print(*[empty] * 5)
[] [] [] [] []

答案 4 :(得分:0)

你可以将字符串化为空,然后使用此打印字符串x次选项,例如

empty = []
print 5*str(empty)  

答案 5 :(得分:0)

您可能想要查看itertools。例如:

import itertools
a=[]
repeat=list(itertools.repeat(a, 10))
print(repeat)

应该给你:

[[], [], [], [], [], [], [], [], [], []]