I have a method in a Python app to write a list of records to a CSV file. Each record is a "football player", which is really just a dictionary. But one of the dictionary items contains a list of weekly scores. I want to write out to CSV a record for each player, and then flatten the list of scores and write that out, too.
My code:
def write_csv_file(filename, year, list_of_players):
print str(datetime.now()) + ' Writing file {0}'.format(OUTPUT_CSV_PATH + filename + '.csv')
print list_of_players
with open(OUTPUT_CSV_PATH + filename + '.csv', 'w+') as f:
writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator = '\n')
writer.writerow(['YEAR', 'FILENAME', 'PLAYER_KEY', 'PLAYER_NAME', 'SEASON_TOTAL', 'CALCULATED_SEASON_TOTAL', 'MEAN', 'MEDIAN', 'STD_DEVIATION', 'CV',
'WK1', 'WK2', 'WK3', 'WK4', 'WK5', 'WK6', 'WK7', 'WK8', 'WK9', 'WK10', 'WK11', 'WK12', 'WK13', 'WK14', 'WK15', 'WK16'])
for item in list_of_players:
writer.writerow([year, filename, item['player_key'], item['player_name'], item['season_total'],
item['calculated_season_total'], item['mean'], item['median'], item['std_deviation'], item['coefficient_of_variation'],
#item['performance_score'],
item['scores'][0],
item['scores'][1],
item['scores'][2],
item['scores'][3],
item['scores'][4],
item['scores'][5],
item['scores'][6],
item['scores'][7],
item['scores'][8],
item['scores'][9],
item['scores'][10],
item['scores'][11],
item['scores'][12],
item['scores'][13],
item['scores'][14],
item['scores'][15]
])
It's the handling of item['scores']
that I'm sure there's a better way. I tried getting a list comprehension to work but never could get it going.
How can I do this better?