7

What's the difference between using File.write() and print>>File,?

Which is the pythonic way to write to file?

>>> with open('out.txt','w') as fout:
...     fout.write('foo bar')
... 

>>> with open('out.txt', 'w') as fout:
...     print>>fout, 'foo bar'
... 

Is there an advantage when using print>>File, ?

Charles
  • 50,943
  • 13
  • 104
  • 142
alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

10

write() method writes to a buffer, which (the buffer) is flushed to a file whenever overflown/file closed/gets explicit request (.flush()).

print will block execution till actual writing to file completes.

The first form is preferred because its execution is more efficient. Besides, the 2nd form is ugly and un-pythonic.

volcano
  • 3,578
  • 21
  • 28
0

The most pythonic way is the .write().

I didn't even know the other way, but it doesn't even work with Python 3.3

A similar way of doing it would be:

fout = open("out.txt", "w")
fout.write("foo bar")
#fout.close() if you were done with the writing
RGS
  • 964
  • 2
  • 10
  • 27
  • 3
    Python 3 changed `print` to a function, so the syntax is different: `print("some string", file=fout)` – Tim Jan 01 '14 at 12:43