2012-05-04 78 views
3

而不是使用write(),在Python 2和3中寫入文本文件的另一種方式是什麼?如何在python 2.x和3.x中直接打印到文本文件?

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

爲什麼你想要其他方式來做到這一點?一般來說,Python做一件事的方法很少。這是故意的,很好。使用「打印」不等於寫,有細微差別。 –

回答

26

可以使用print_functionfuture import從python3得到print()行爲python2:

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

如果您不希望該功能追加末斷行,加end=''關鍵字參數調用print()

但是,考慮使用f.write('some text'),因爲這更清晰並且不需要導入__future__

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

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

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

請注意,這將在最後用換行符('\ n')打印 – jamylak