0
with open("classA.csv" , "a", newline = "") as fp:
     a = csv.writer(fp, delimiter = ",")
     data = [("{0} has scored: {1} / 10\n ".format(name,score))]
     a.writerows(data) 

I am trying to create a maths quiz that calculates the final result and then writes this result to an excel file. This is my code so far but when I look into excel, I see that the entire statement in data is stretched out across the row and would like this:

| B | o | b | h | a | s | s | c | o | r | e | d | : | 9 | / | 1 | 0

How would I be able to print out like this:

| Bob has scored: | 9/10 |

Thanks for any help!

1
  • writerows expects an iterable of iterables Commented Oct 6, 2015 at 19:04

2 Answers 2

2

You need to provide a tuple of columns in the list that you pass to writerows.

Each element in the tuple will be a column in the resulting file, and all the tuples in the list represent the rows.

For example, if you want to output:

Bob,2
Joe,3
Bill,5

Then you need to create a list like this:

[('Bob', 2), ('Joe', 3), ('Bill', 5)]

To implement the same in your example, try this version:

col1, col2 = '{} has scored:','{}/10'

with open('classA.csv', 'a') as fp:
   writer = csv.writer(fp, delimiter=',')
   data = [(col1.format(name), col2.format(score))]
   writer.writerows(data)

You also don't need to add the \n

Sign up to request clarification or add additional context in comments.

Comments

0

your delimiter is ',' so you should try: data = [("{0} has scored,{1} / 10\n ".format(name,score))] or set the delimiter to ':'

1 Comment

The problem is that writerows is iterating over the string, the delimiter isn't a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.