print 输出到文件

content = """We have seen thee, queen of cheese,
Lying quietly at your ease,
Gently fanned by evening breeze,
Thy fair form no flies dare seize.
All gaily dressed soon you'll go
To the great Provincial show,
To be admired by many a beau
In the city of Toronto.
Cows numerous as a swarm of bees,
Or as the leaves upon the trees,
It did require to make thee please,
And stand unrivalled, queen of cheese.
May you not receive a scar as
We have heard that Mr. Harris
Intends to send you off as far as
The great world's show at Paris.
Of the youth beware of these,
For some of them might rudely squeeze
And bite your cheek, then songs or glees
We could not sing, oh! queen of cheese.
We'rt thou suspended from balloon,
You'd cast a shade even at noon,
Folks would think it was the moon
About to fall and crush them soon.
"""

1.python3版本

f = open('poem.txt','w')
print(content,file=f)
f.close()

2.python2版本

f = open('poem.txt','w')
print >> f,content  #使用输出重定向 ,注意只是将内容写入了文件的缓冲区中,还没有写入文件
f.close()  #关闭文件描述符,将文件缓冲区中的内容从内存写入磁盘文件
原文地址:https://www.cnblogs.com/hupeng1234/p/6655882.html