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.
"""))
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
输出:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
>>> 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!
>>> # 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'