迭代通过Python字典N个项目进行CSV写入

时间:2018-01-29 01:37:58

标签: python csv dictionary

我有一堆用于创建CSV文件的方法,这些方法开始让我觉得我真的在重复自己。这是一对夫妇:

def genSmsOutputFile(self, smsDict):
    with open(settings.MEDIA_ROOT + 'smsOutput.csv', 'w+') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        writer.writerow( ['電話番号','会員ID','TEL1','TEL2','TEL3','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)',] )
        for key, value in smsDict.items():
            phoneNumber = value[2] + value[3] + value[4]
            writer.writerow( [ phoneNumber, value[0], value[2], value[3], value[4],'','','','','','','','','','','',''] )
        return 'smsOutput.csv'

def genMailOutputFile(self, okMailMaga):
    with open(settings.MEDIA_ROOT + 'mailMagaOutput.csv', 'w+') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        writer.writerow( [ '会員id','e-mail','お名前(姓)','お名前(名)','購入回数' ] )
        for key, value in okMailMaga.items():
            writer.writerow( [ value[0], value[1], value[2], value[3], value[4] ] )
        return settings.MEDIA_ROOT + 'mailMagaOutput.csv'

我正在创建函数_writeOutputToFile(self, dictionary, columnNames):

但我发现自己陷入了如何编写这条线:

 writer.writerow([value[0], value[1], value[2], value[3], value[4]])

有没有办法在一次循环迭代中动态地从字典中获取整行CSV

1 个答案:

答案 0 :(得分:4)

您可以连接列表以获取更大的列表。举个例子:

writer.writerow( [ phoneNumber, value[0], value[2], value[3], value[4],'','','','','','','','','','','',''] )

可能是:

writer.writerow([phoneNumber, value[0]] + value[2:5] + [''] * 12)