how to print directly to a text file in both python 2.x and 3.x?

萝らか妹 提交于 2019-12-10 01:04:31

问题


Instead of using write(), what are the other way to write to a text file in Python 2 and 3?

file = open('filename.txt', 'w')
file.write('some text')

回答1:


You can use the print_function future import to get the print() behaviour from python3 in python2:

from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)

If you do not want that function to append a linebreak at the end, add the end='' keyword argument to the print() call.

However, consider using f.write('some text') as this is much clearer and does not require a __future__ import.




回答2:


f = open('filename.txt','w')

# For Python 3 use
print('some Text', file=f)

#For Python 2 use
print >>f,'some Text'


来源:https://stackoverflow.com/questions/10445726/how-to-print-directly-to-a-text-file-in-both-python-2-x-and-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!