我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
值得注意的是,当你使用交互式Python shell或Jupyter Notebook检查字符串时,\n和其他反划字符串(如\t)会逐字呈现:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'
换行符、制表符和其他特殊的非打印字符只有在打印或写入文件时才会呈现为空白:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!
其他回答
这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。
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.
"""))
在Python 3中,该语言会在平台的原生表示中为你编码换行符。这意味着在Windows上是\r\n,而在成熟的系统上只是\n。
即使在U*x系统上,以文本模式读取Windows行结束符的文件也会返回正确的文本结果,即在\n字符之前的任何\r字符都会被无声地删除。
如果需要完全控制文件中的字节,则可以使用二进制模式。然后,每个字节恰好对应一个字节,Python不执行任何转换。
>>> # Write a file with different line endings, using binary mode for full control
>>> with open('/tmp/demo.txt', 'wb') as wf:
... wf.write(b'DOS line\r\n')
... wf.write(b'U*x line\n')
... wf.write(b'no line')
10
9
7
>>> # Read the file as text
>>> with open('/tmp/demo.txt', 'r') as text:
... for line in text:
... print(line, end='')
DOS line
U*x line
no line
>>> # Or more demonstrably
>>> with open('/tmp/demo.txt', 'r') as text:
... for line in text:
... print(repr(line))
'DOS line\n'
'U*x line\n'
'no line'
>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(line)
b'DOS line\r\n'
b'U*x line\n'
b'no line'
>>> # Open in binary, but convert back to text
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(line.decode('utf-8'), end='')
DOS line
U*x line
no line
>>> # Or again in more detail, with repr()
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(repr(line.decode('utf-8')))
'DOS line\r\n'
'U*x line\n'
'no line'
值得注意的是,当你使用交互式Python shell或Jupyter Notebook检查字符串时,\n和其他反划字符串(如\t)会逐字呈现:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'
换行符、制表符和其他特殊的非打印字符只有在打印或写入文件时才会呈现为空白:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!
与平台无关的断行符:Linux、Windows和iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
示例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