Tori Elstrom
Tori Elstrom

Reputation: 61

CSV writer stops at one row

How do you write all data to CSV? Currently this is creating one complete row. But does not move on. I tried writer.rows, I tried "Cards".

Cards = Card.where(q='set.name:generations supertype:pokemon')
for card in Cards:

    card = (card.name, card.types, card.supertype, card.subtypes, card.number, card.rarity, card.nationalPokedexNumbers, card.id, card.set.name, card.set.series)
    rows = card
    

with open ('pokemontest3.csv', 'w', newline='', encoding='utf-8') as csv_file: 
    csvwriter = csv.writer(csv_file)

    csvwriter.writerow(rows)

Upvotes: 0

Views: 344

Answers (1)

tdelaney
tdelaney

Reputation: 77407

You keep overwriting rows in your for loop. When its done, only the last card is in rows. If you run the loop after you've created the writer, you can just write as you go.

with open ('pokemontest3.csv', 'w', newline='', encoding='utf-8') as csv_file: 
    csvwriter = csv.writer(csv_file)
    Cards = Card.where(q='set.name:generations supertype:pokemon')
    for card in Cards:
        card = (card.name, card.types, card.supertype, card.subtypes, card.number, card.rarity, card.nationalPokedexNumbers, card.id, card.set.name, card.set.series)
        csvwriter.writerow(card)

Upvotes: 1

Related Questions