在 Windows 的 Python 中向文件追加新行

Appending a new line to a file in Python on Windows

f = open(fn, 'ab')
f.write("\nline\n\ntest\n\ntest")

文件显示:

linetesttest

因此所有 \n 个字符都将被忽略。我认为以二进制模式追加 ('ab') 应该启用正确的 \n 行为。

使用 \r\n 代替 \n 是可行的。我在 Windows.

谁能解释一下?

以二进制模式打开是问题。不要使用二进制模式,它会做你期望的。