How to append new data onto a new line How to append new data onto a new line python python

How to append new data onto a new line


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.


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.


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