1

I am adding names and scores into a file and was trying to figure out how to start a newline after writing data to the file. This is my code so far, but when I go on in the file, all of the variables are on the same line:

print "That's the game folks! You finished with a final score of...", points, 'points! Good game, you made the high score list! What is your name?'
name = raw_input()
w = open('Highscores', 'a')
w.write(name)
w.write(str(points))
w.close()
0

3 Answers 3

1

Use \n for new lines on unix or \r\n for windows. Just add to the end of the string.

w.write(str(points) + '\n')

or

print "That's the game folks! You finished with a final score of...", points, 'points! Good game, you made the high score list! What is your name?\n'
Sign up to request clarification or add additional context in comments.

Comments

0

This becomes prettier in Py3:

print("That's the game folks! You scored %i points! Your name?" % points)
with open('Highscores', 'a') as w:
    print('%s %i' % (input(), points), file=w)

If you only want a single entry per user (i.e. the highest score of a particular user and no duplicates), you could use a dictionary and do something like this:

>>> from ast import literal_eval
>>> def save_score(name, score):
...     try:
...         d = literal_eval(open('score').read())
...     except:
...         d = {}
...     if name not in d or d[name] < score:
...         d[name] = score
...         open('score', 'w').write(str(d))
...
>>> save_score('Jack', 5)
>>> save_score('Jill', 10)
>>> open('score').read()
"{'Jill': 10, 'Jack': 5}"

Comments

0

Do the following,

print(name, points, sep=":", file="Highscores") # Mike:23 

You don't even have to do str(points). Works for any data type. And adds a newline by default. It is very efficient compared to custom acrobatics using .write().(Beazly)

Comments

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.