将多个空白字段写入csv python

2024-04-27 05:00:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大量的csv要导入DB表。你知道吗

我的导入模板要求一组列。如果我的输入数据只有几个所需的列(在我的例子中只有3个),我想把它们放在各自的列中,不满意的列留空。你知道吗

例如,listList1Column将进入我的模板的“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对象。你知道吗

如果有人有更好的建议如何做这一点不同或更有效的整体,让我知道。你知道吗


Tags: csv数据in模板列表foremptyrow
3条回答

试试print str(empty) * 5。你知道吗

如您所料,乘法只适用于字符串。你知道吗

使用for循环。你知道吗

for _ in range(5):
    print listname,

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

您可以使用一个简单的while

empty = []
i = 0
while i < 5:
    print empty
    i = i + 1

相关问题 更多 >