Mark Lewis
Mark Lewis

Reputation: 1

Writer (cvs) is treating each character as a field

Writer is writing a list to a csv file but treating each character as a field:

nteams =16
c = 1
teams = []

while c <= nteams:
    teams.append("Team " + str(c))
    c = c + 1

This bit creates the list properly and returns the following teams:

['Team 1', 'Team 2', 'Team 3', 'Team 4']

Then I do this:

import csv

# writing the data into the file
with open ('teams.csv','w') as f:
    wtr = csv.writer(f)
    wtr.writerows(teams) 

But this bit returns this to the csv file:

T,e,a,m, ,1
T,e,a,m, ,2
T,e,a,m, ,3
T,e,a,m, ,4

This is not good. Help please.

I've tried changing the open mode "WB" and "W":

with open ('teams.csv','w') as f:
                        ^

Upvotes: 0

Views: 41

Answers (1)

PCDSandwichMan
PCDSandwichMan

Reputation: 2120

The writerows method expects a list of lists. You are passing it a list of strings. You can use a list comprehension to create a list of lists:

import csv

nteams =16
c = 1
teams = []

while c <= nteams:
    teams.append("Team " + str(c))
    c = c + 1

with open ('teams.csv','w') as f:
    wtr = csv.writer(f)
    wtr.writerows([[team] for team in teams])

Output:

Team 1
Team 2
Team 3
Team 4

Upvotes: 0

Related Questions