How to append new data onto a new line

PythonFile IoAppend

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

If you want a newline, you have to write one explicitly. The usual way is like this:

hs.write(name + "\n")

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:

hs.write("{}\n".format(name))

All of this is explained in the Input and Output chapter in the tutorial.

Solution 2 - Python

In Python >= 3.6 you can use new string literal feature:

with open('hst.txt', 'a') as fd:
    fd.write(f'\n{name}')

Please notice using 'with statment' will automatically close the file when 'fd' runs out of scope

Solution 3 - Python

All answers seem to work fine. If you need to do this many times, be aware that writing

hs.write(name + "\n")

constructs a new string in memory and appends that to the file.

More efficient would be

hs.write(name)
hs.write("\n")

which does not create a new string, just appends to the file.

Solution 4 - Python

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,

with open('hst.txt') as fobj:
    text = fobj.read()

name = 'Bob'

with open('hst.txt', 'a') as fobj:
    if not text.endswith('\n'):
        fobj.write('\n')
    fobj.write(name)

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.

Solution 5 - Python

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

Solution 6 - Python

There is also one fact that you have to consider. You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code

  1. first checks if the file is empty
  2. If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.

Code:

import os

def storescores():
hs = open("hst.txt","a")
if(os.path.getsize("hst.txt") > 0):
   hs.write("\n"+name)
else:
   hs.write(name)

hs.close()

Solution 7 - Python

I presume that all you are wanting is simple string concatenation:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name + " ")
   hs.close() 

Alternatively, change the " " to "\n" for a newline.

Solution 8 - Python

import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)

Solution 9 - Python

You need to change parameter "a" => "a+". Follow this code bellows:

def storescores():
hs = open("hst.txt","a+")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanH2796View Question on Stackoverflow
Solution 1 - PythonabarnertView Answer on Stackoverflow
Solution 2 - PythonVlad BezdenView Answer on Stackoverflow
Solution 3 - Pythonserv-incView Answer on Stackoverflow
Solution 4 - PythonWyrmwoodView Answer on Stackoverflow
Solution 5 - PythonS3445View Answer on Stackoverflow
Solution 6 - PythonρssView Answer on Stackoverflow
Solution 7 - PythonDaniel CasserlyView Answer on Stackoverflow
Solution 8 - PythonmarkroxorView Answer on Stackoverflow
Solution 9 - PythonSang9xproView Answer on Stackoverflow