111

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
RyanH2796
  • 1,119
  • 2
  • 7
  • 8

10 Answers10

115

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
33

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

Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
28

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.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
  • 9
    This is a tradeoff between constructing a new string in memory with `BINARY_ADD` vs doing a `LOAD_FAST` to get hs(can be optimized away outsize the loop), `LOAD_ATTR` to get `write`, and a `CALL_FUNCTION`(relatively high overhead) twice, so it may depend on the size of the `name` string. In the end, benchmarking is the best way to see(and only if you need this speed-up). – Bryce Guinta Jul 01 '16 at 19:05
23

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.

Wyrmwood
  • 3,340
  • 29
  • 33
  • This method is key to appending to JSON documents, where an extra newline at either the top or bottom of the file is punishable by death. You can't blindly add it; it must be conditional on whether something already exists. – Excel Help Oct 30 '21 at 10:35
  • @ExcelHelp if the question mentioned json, I would have recommended using json load/dump with the desired formatting. The filename is `hst.txt`. I would not recommend manual parsing of a json, except perhaps as an exercise. – Wyrmwood Dec 21 '21 at 23:18
6

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.

S3445
  • 77
  • 1
  • 2
5

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()
ρss
  • 5,115
  • 8
  • 43
  • 73
2

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.

Tim
  • 41,901
  • 18
  • 127
  • 145
Daniel Casserly
  • 3,552
  • 2
  • 29
  • 60
  • 1
    He wants a newline between them, not a space. (It's hard to tell from the question because his formatting is broken, but if you look at the question source, he typed a newline.) – abarnert Feb 17 '14 at 21:46
  • Thanks - I did address that just in case but I hadn't checked the formatting. – Daniel Casserly Feb 17 '14 at 21:48
  • Yeah, I'm sorry, I'm new to this website and couldn't quite get my head around the formatting of questions but I've got it now, thanks – RyanH2796 Feb 17 '14 at 21:50
  • @user3320839: Usually when I edit a question I add a comment explaining what I did, but in this case I was pretty sure you would probably figure it out on your own. And no harm done; nobody writes perfect questions their first try. – abarnert Feb 17 '14 at 21:55
1
import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)
markroxor
  • 5,928
  • 2
  • 34
  • 43
0
f=open("Python_Programs/files_forhndling.txt","a+")
inpt=str(input("Enter anything:\n>>"))
f.write(inpt)
f.write("\n")
print("Data inserted Successfully")
f.close()

welcome to file handling
new line
file handling in python
123456
78875454

✔ Output CLICK BELOW & SEE ✔


OUTPUT 1

CODE

Shubham-Misal
  • 33
  • 1
  • 7
-5

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

def storescores():
hs = open("hst.txt","a+")
Sang9xpro
  • 435
  • 5
  • 8
  • Have you tried your own code. I don't think it is working. – kennyut Jul 29 '19 at 15:18
  • Yes. Ofcouse it's working. I usually use it in my project! – Sang9xpro Aug 02 '19 at 10:04
  • a and a+ are the same thing – Jake Sep 28 '21 at 16:42
  • 'a+' isn't the exact solution, and maybe don't implicitly suggest leaving the resource open by not explicitly including the close in your example. ¯\_(ツ)_/¯ – Justin Jun 15 '22 at 17:27
  • This "a" option helped me a lot, **r** = Open text file for reading. Prepend; **r+** = Open for reading and writing. Prepend; **w** = Truncate file to zero length or create text file for writing. Write; **w+** = Open for reading and writing. Write; **a** = Open for writing. Append; **a+** = Open for reading and writing. Append. – Luis Sep 22 '22 at 00:46