回车不予转换

时间:2015-12-24 18:31:00

标签: python newline

我需要在新行上写每个字符串。我使用这段代码。

f = open('log.txt', 'a')<br>
f.write("sting to write/n")<br>
f.close()

但不是添加新行,而是在字符串末尾打印/ n个字符 我尝试了'/ r','/ r / n'和'/ n / r'。同样的事情。

谢谢!

3 个答案:

答案 0 :(得分:3)

你正在逃避换行符错误。使用反斜杠 - 而不是foreslash:

f = open('log.txt', 'a')
f.write("sting to write\n")
f.close()

另请注意,这是&#34;换行符&#34;。 回车符\r

答案 1 :(得分:2)

换行符不是/n,而是\n

答案 2 :(得分:1)

换行符的正确字符串为\n,而不是/n。在Python上,最好使用os.linesep,因为这对于您所使用的系统来说是正确的:它可以是\n\r\r\n。此外,执行文件I / O时使用with关键字,以避免在出现异常情况时手动关闭文件:

import os
with open('log.txt', 'a') as f:
    f.write("string to write" + os.linesep)
相关问题