如何将新数据追加到新行上

我的代码是这样的:

def storescores():


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

所以如果我运行它,输入“ Ryan” 然后再运行一次,输入“ Bob” 文件 hst.txt 看起来像

RyanBob

而不是

Ryan
Bob

我该怎么补救?

308571 次浏览

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.

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.

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()

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.

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.

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

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.

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

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

def storescores():
hs = open("hst.txt","a+")
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