0

I have two strings that i want to put into a txt file but when I try and write then, it's only on the first line, I want the string to be on separate lines how do I do so?

Here is the writing part of my code btw:

saveFile = open('points.txt', 'w') saveFile.write(str(jakesPoints)) saveFile.write(str(alexsPoints)) saveFile.close 

if jakesPoints was 10 and alexsPoints was 12 then the text file would be

1012 

but i want to to be

10 12 

2 Answers 2

1

You can use a newline character (\n) to move to a new line. For your example:

with open('points.txt', 'w') as saveFile: saveFile.write("{}\n".format(jakesPoints)) saveFile.write("{}\n".format(alexsPoints)) 

The other things to note:

  • It is helpful to open files using with - this will take care of opening and closing the file automatically (which is typically preferred over trying to remember to .close()).
  • The {}.format() section is used to convert your numbers to a string and add the newline character. I found https://pyformat.info/ explained the string formatters pretty good and highlight all the main advantages.
Sign up to request clarification or add additional context in comments.

Comments

1
with open('points.txt', 'w') as saveFile: saveFile.write(str(jakesPoints)) saveFile.write("\n") saveFile.write(str(alexsPoints)) 

See difference betweenw and a used in open(). Also see join() .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.