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

与Java(以字符串形式)相比,您可以执行"First Line\r\nSecond Line"

那么,为了在常规文件中写多行,您将如何在Python中执行此操作?


ABOUTYOU
浏览 911回答 3
3回答

陪伴而非守候

这取决于您想做的正确程度。\n通常会做的工作。如果您确实想解决问题,请在os包中查找换行符。(实际上称为linesep。)注意:使用Python API写入文件时,请勿使用os.linesep。随便用\n; Python会自动将其转换为适合您平台的换行符。

弑天下

新行字符为\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 youI am testing the new line escape sequencethis 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 youI am testing the new line escape sequencethis seems to work
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python