Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append new data onto a new line

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?

like image 960
RyanH2796 Avatar asked Feb 17 '14 21:02

RyanH2796


People also ask

How do you append a line next to a line in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

How do you add a new line to a text file in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do I add a new line to a text file?

" \r " is a carriage return and " \n " is a line-feed; the pair forms a Windows newline.

What is the symbol used for adding a new content in new line?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


8 Answers

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.

like image 183
abarnert Avatar answered Oct 02 '22 07:10

abarnert


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

like image 39
Vlad Bezden Avatar answered Oct 02 '22 09:10

Vlad Bezden


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.

like image 34
serv-inc Avatar answered Oct 02 '22 08:10

serv-inc


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.

like image 36
Wyrmwood Avatar answered Oct 02 '22 09:10

Wyrmwood


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.

like image 42
S3445 Avatar answered Oct 02 '22 08:10

S3445


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()
like image 23
ρss Avatar answered Oct 02 '22 08:10

ρss


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.

like image 41
Daniel Casserly Avatar answered Oct 02 '22 07:10

Daniel Casserly


import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)
like image 23
markroxor Avatar answered Oct 02 '22 08:10

markroxor