我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
与平台无关的断行符:Linux、Windows和iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
其他回答
各种等效方法
使用打印
默认情况下,打印已经追加了换行符!
with open("out.txt", "w") as f:
print("First", file=f)
print("Second", file=f)
等同于:
with open("out.txt", "w") as f:
print("First\nSecond", file=f)
要打印而不自动添加换行符,使用sep=""(因为sep="\n"是默认值):
with open("out.txt", "w") as f:
print("First\nSecond\n", sep="", file=f)
使用f.write
对于以文本模式打开的文件:
with open("out.txt", "w") as f:
f.write("First\nSecond\n")
对于以二进制模式打开的文件,写入文件时不会自动将\n转换为特定于平台的行结束符。要强制使用当前平台的换行符,请使用os。Linesep代替\n:
with open("out.txt", "wb") as f:
f.write("First" + os.linesep)
f.write("Second" + os.linesep)
输出文件
视觉:
First
Second
在Linux上,换行符将以\n分隔:
First\nSecond\n
在Windows中,换行符将以\r\n分隔:
First\r\nSecond\r\n
为了避免以文本模式打开的文件自动将\n转换为\r\n,请使用open("out.txt", "w", newline="\n")打开文件。
这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。
import textwrap
file.write(textwrap.dedent("""
Life's but a walking shadow, a poor player
That struts and frets his hour upon the stage
And then is heard no more: it is a tale
Told by an idiot, full of sound and fury,
Signifying nothing.
"""))
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
示例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
新的行字符是\n。它用于字符串内部。
例子:
print('First line \n Second line')
其中\n是换行符。
这将产生如下结果:
First line
Second line
如果使用Python 2,则不对打印函数使用圆括号。
Java字符串文字中的大多数转义字符在Python中也有效,例如“\r”和“\n”。