Reputation: 2351
I have a bunch of methods for creating CSV files that are starting to make me feel like I am really repeating myself. Here are a couple:
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'
I am working to create the function _writeOutputToFile(self, dictionary, columnNames):
But I am finding myself stuck on how I would write the line:
writer.writerow([value[0], value[1], value[2], value[3], value[4]])
Is there some way to grab an entire row of the CSV from a dictionary in one loop iteration dynamically?
Upvotes: 1
Views: 31
Reputation: 49812
You can concatenate lists to get a larger list. So as an example:
writer.writerow( [ phoneNumber, value[0], value[2], value[3], value[4],'','','','','','','','','','','',''] )
could be:
writer.writerow([phoneNumber, value[0]] + value[2:5] + [''] * 12)
Upvotes: 4