My code looks like this:
def storescores():
hs = open("hst.txt","a")
hs.write(name)
hs.close()
so if I run it and enter "Ryan" then run it again and enter "Bob" the file hst.txt looks like
RyanBob
instead of
Ryan
Bob
How do I fix this?
If you want a newline, you have to write one explicitly. The usual way is like this:
This uses a backslash escape,
\n
, which Python converts to a newline character in string literals. It just concatenates your string,name
, and that newline character into a bigger string, which gets written to the file.It's also possible to use a multi-line string literal instead, which looks like this:
Or, you may want to use string formatting instead of concatenation:
All of this is explained in the Input and Output chapter in the tutorial.
I had the same issue. And I was able to solve it by using a formatter.
I hope this helps.
I presume that all you are wanting is simple string concatenation:
Alternatively, change the " " to "\n" for a newline.
In Python >= 3.6 you can use new string literal feature:
Please notice using 'with statment' will automatically close file when it fd runs out of scope
All answers seem to work fine. If you need to do this many times, be aware that writing
constructs a new string in memory and appends that to the file.
More efficient would be
which does not create a new string, just appends to the file.
The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.