在编写文件时,如何在Python上指定新行?

2024-04-19 10:33:49 发布

您现在位置:Python中文网/ 问答频道 /正文

与Java(字符串)相比,您可以做一些类似"First Line\r\nSecond Line"的事情。

那么,在Python中,为了将多行代码写到一个常规文件中,您将如何做到这一点呢?


Tags: 文件字符串代码linejava事情常规first
3条回答

新行字符是\n。它用在一根绳子里面。

示例:

    print 'First line \n Second line' 

其中\n是换行符。

这将产生以下结果:

First line
 Second line

您可以单独写入新行,也可以在单个字符串中写入,这样更容易。

例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通常会完成这项工作。如果您真的想把它弄好,可以在^{} package中查找换行符。(它实际上叫做linesep。)

注意:当使用Python API写入文件时,不要使用os.linesep。只需使用\n;Python会自动将其转换为适合您的平台的换行符。

相关问题 更多 >