0

I am writing data from a list to a csv file like this:

def writeToCsv(list, max):
    writer = csv.writer(open('file.csv', 'wb'), delimiter=' ')
    for x in range(0,max):
        writer.writerow(list[x]['year'])

This fills the first column with the years which is great. Now I want to fill the next column with the 'name' in the list. How can I run the above code again but have it fill the next column instead of writing over the first column with the 'name'?

buydadip
  • 8,890
  • 22
  • 79
  • 154
Cybernetic
  • 12,628
  • 16
  • 93
  • 132
  • 1
    When using the `csv` module, you should structure your code so you write one *row* at a time, not one column. That's why the method is called `writerow`. – BrenBarn Jan 25 '15 at 23:03

1 Answers1

1

Just give a list to writerow:

def writeToCsv(list, max):
    writer = csv.writer(open('file.csv', 'wb'), delimiter=' ')
    for x in range(0,max):
        writer.writerow([list[x]['year'], list[x]['name']])

Notice you can do this:

def writeToCsv(lst, limit):
    # use a context manager to close the file for you when you're done
    with open('file.csv', 'wb') as f:
        writer = csv.writer(f, delimiter=' ')
        # takes the first `max` dictionaries from the list
        for item in lst[:limit]:
            writer.writerow([item['year'], item['name']])

This is using slicing and the with context manager.

note: I've changed the names of the function arguments so that you don't shdow the built-in functions list and max. (thanks @Padraic Cunningham)

Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88