Harry Beggs Harry Beggs -4 years ago 296
Python Question

Python 2.7 CSV writing format not correct

I am currently trying to get a leader board working. The leader board will only store the score. I am trying to write the scores to the csv file. Here is my code for the write:

if col:
with open("rec_Scores.csv", "a") as f:
w = csv.writer(f, delimiter = ",")
w.writerow(str(curr_score) + "\n")
crashed = True


When this is run the csv file ends up like this: https://gyazo.com/19c9007827498fb5cf847535167d5841

I think it has to do with the score being converted into a string, but when I do not convert the score I get the error:

Traceback (most recent call last):
File "C:\Users\Harry\Desktop\Desktop\Computing Project\Galaxian.py", line 173, in <module>
w.writerow(curr_score + "\n")
TypeError: unsupported operand type(s) for +: 'int' and 'str'


This is the first time I have been working with csv files in Python so I have probably made a small silly mistake but any help will be much appreciated. Thanks.

Answer Source

You don't need to add linebreaks (\n) yourself. The csv.writer will do that for you.

if col:
    with open("rec_Scores.csv", "a") as f:
        w = csv.writer(f, delimiter = ",")
        w.writerow(curr_score)
    crashed = True

The odd result you get when you convert curr_score to a string is because a string in python is iterable (you can say for char in "abc":). writerow is set up to accept an iterable, creating one field in the row for each member of the iterable. So writerow is thinking you want a number of columns, each containing one character.

If you want to add a string as the only element on a row, you need to enclose it in another iterable, for instance, a tuple:

if col:
    with open("rec_Scores.csv", "a") as f:
        w = csv.writer(f, delimiter = ",")
        w.writerow((str(curr_score),)) #note the extra brackets and comma
    crashed = True
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download