向文件写入新行 (Python 3)

Write a new line to a file (Python 3)

因此,在阅读了同一个问题的许多实例后,我仍然被困住了。为什么这个函数不是每次都换行写?:

def addp(wrd,pos):
    with open('/path/to/my/text/file', 'w') as text_file:
        text_file.write('{0} {1}\n'.format(wrd,pos))

看来 \n 应该可以解决问题。我错过了什么吗?

我是 运行 Ubuntu 15.04

它应该一直在向文件写入换行符,问题可能是您以 w 模式打开文件,这会导致文件被覆盖,因此每次调用上述函数它仅用您发送的 wrd,pos 完全覆盖文件,因此文件仅包含一行。

您应该尝试使用 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))