Question

I have been using multiple code snippets to create a solution that will allow me to write a list of players in a football team to a csv file.

import csv

data = []
string = input("Team Name: ")
fName = string.replace(' ', '') + ".csv"

print("When you have entered all the players, press enter.")

# while loop that will continue allowing entering of players
done = False
while not done:
    a = input("Name of player: ")
    if a == "":
        done = True
    else:
        string += a + ','
        string += input("Age: ") + ','
        string += input("Position: ")

print (string)

file = open(fName, 'w')
output = csv.writer(file)

for row in string:
    tempRow = row
    output.writerow(tempRow)

file.close()

print("Team written to file.")

I would like the exported csv file to look like this:

player1,25,striker
player2,27,midfielder

and so on. However, when I check the exported csv file it looks more like this:

p
l
a
y
e
r
,
2
5

and so on.

Does anyone have an idea of where i'm going wrong?

Many thanks Karl

Was it helpful?

Solution

Your string is a single string. It is not a list of strings. You are expecting it to be a list of strings when you are doing this:

for row in string:

When you iterate over a string, you are iterating over its characters. Which is why you are seeing a character per line.

Declare a list of strings. And append every string to it like this:

done = False
strings_list = []
while not done:
    string = ""
    a = input("Name of player: ")
    if a == "":
        done = True
    else:
        string += a + ','
        string += input("Age: ") + ','
        string += input("Position: ") + '\n'
        strings_list.append(string)

Now iterate over this strings_list and print to the output file. Since you are putting the delimiter (comma) yourself in the string, you do not need a csv writer.

a_file = open(fName, 'w')
for row in strings_list:
    print(row)
    a_file.write(row)
a_file.close()

Note: string is a name of a standard module in Python. It is wise not to use this as a name of any variable in your program. Same goes for your variable file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top