Python 如何将新数据附加到新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21839803/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append new data onto a new line
提问by RyanH2796
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
所以如果我运行它并输入“Ryan”然后再次运行它并输入“Bob”文件 hst.txt 看起来像
RyanBob 
instead of
代替
Ryan
Bob
How do I fix this?
我该如何解决?
回答by abarnert
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.
这使用反斜杠转义,\n,Python 将其转换为字符串文字中的换行符。它只是将您的字符串 ,name和该换行符连接成一个更大的字符串,然后写入文件。
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 Outputchapter in the tutorial.
所有这些都在教程的输入和输出章节中进行了解释。
回答by Daniel Casserly
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.
或者,将换行符的 " " 更改为 "\n"。
回答by ρss
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
您还必须考虑一个事实。在添加任何内容之前,您应该首先检查您的文件是否为空。因为如果您的文件是空的,那么我认为您不想在文件的开头添加一个空白的新行。这段代码
- first checks if the file is empty
- 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.
- 首先检查文件是否为空
- 如果文件为空,那么它只会将您的输入文本添加到文件中,否则它将添加一个新行,然后将您的文本添加到文件中。您应该使用 try catch foros.path.getsize()来捕获任何异常。
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()
回答by serv-inc
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.
它不会创建新字符串,只是附加到文件中。
回答by S3445
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.
我希望这有帮助。
回答by Vlad Bezden
In Python >= 3.6 you can use new string literalfeature:
在 Python >= 3.6 中,您可以使用新的字符串文字功能:
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
请注意使用 ' with statment' 将在 'fd' 超出范围时自动关闭文件
回答by Wyrmwood
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 beforeyou 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.
您可能想在 name 后添加换行符,也可能不想,但无论如何,这不是您问题的答案。
回答by markroxor
import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)
回答by Sang9xpro
You need to change parameter "a" => "a+". Follow this code bellows:
您需要更改参数“a”=>“a+”。遵循以下代码:
def storescores():
hs = open("hst.txt","a+")

