我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
Use:
"{}\n{}\n{}".format(
"line1",
"line2",
"line3"
)
我个人更喜欢这种形式。
其他回答
'\n'也是一样,不过你可能不需要'\r'。在Java版本中使用它的原因是什么?如果你确实需要/想要它,你也可以在Python中以同样的方式使用它。
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
示例1
输入
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
你可以把“\n”分开写:
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")
输出
hello how are you
I am testing the new line escape sequence
this seems to work
示例2
输入
正如其他人在之前的回答中指出的那样,将\n放在字符串中的相关点:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"
file.write(line)
输出
hello how are you
I am testing the new line escape sequence
this seems to work
在Python中,你可以只使用换行符,即\n
简单的解决方案
如果只调用print而不带任何参数,它将输出一个空行。
print
你可以像这样将输出管道到一个文件中(考虑到你的例子):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
它不仅与操作系统无关(甚至不需要使用操作系统包),而且比将\n放在字符串中更具可读性。
解释
print()函数有一个可选的关键字参数,用于字符串的结尾,称为end,默认为操作系统的换行符,例如。\ n。所以,当你调用print('hello')时,Python实际上打印的是'hello' + '\n'。这意味着当你只调用print而不带任何参数时,它实际上打印的是" + '\n',结果是换行符。
替代
使用多行字符串。
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
这取决于你想要多正确。\n通常会做这项工作。如果你真的想要正确,你可以在os包中查找换行符。(这实际上叫做linesep。)
注意:当使用Python API写入文件时,不要使用os.linesep。只使用\n;Python会自动将其转换为适合您平台的换行符。