How to load data from a CSV file, manipulate it and write it to another CSV in Python

advertisements

I'm just getting my feet wet with Python and have been looking for the answer for the past few hours. I have a CSV file with a list of all lowercase names as rows. I'm trying to capitalize the first letter of each and save it to a new file. Here's what I have so far but I can't get it to manipulate the data in the CSV.

import csv

input_file = open('file_to_read.csv', 'rb')
output_file = open('file_to_write.csv', 'wb')

reader = csv.reader(input_file)
writer = csv.writer(output_file)

for row in reader:
    data = row.capitalize()
    writer.writerow(data)

input_file.close()
output_file.close()

The error I'm getting is:

AttributeError: 'list' object has no attribute 'capitalize'


capitalize is the method of string but not the method of list.

Use data = [x.capitalize() for x in row] instead