[英]Write a new line to a file (Python 3)
So, after reading many instances of this same question being answered, I'm still stuck. 因此,在阅读了同一个问题的许多实例后,我仍然被困住了。 Why is this function not writing on a new line every time?: 为什么这个函数每次都不写新行?:
def addp(wrd,pos):
with open('/path/to/my/text/file', 'w') as text_file:
text_file.write('{0} {1}\n'.format(wrd,pos))
It would seem as though the \\n
should be doing the trick. 似乎\\n
应该正在做这个伎俩。 Am I missing something? 我错过了什么吗?
I'm running Ubuntu 15.04 我正在运行Ubuntu 15.04
It should be writing newline to the file all the time, the issue maybe that you are openning the file in w
mode, which causes the file to be overwritten , hence for each call to the above function it completely overwrites the file with just the wrd,pos
you send in , so the file only contains a single line. 它应该始终在文件中写入换行符,问题可能是你在w
模式下打开文件,导致文件被覆盖,因此对于上述函数的每次调用,它只用wrd,pos
完全覆盖文件wrd,pos
发送你的位置,所以该文件只包含一行。
You should try using a
mode, which is for appending to the file. 您应该尝试使用a
模式,该模式用于附加到文件。
def addp(wrd,pos):
with open('/path/to/my/text/file', 'a') as text_file:
text_file.write('{0} {1}\n'.format(wrd,pos))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.