Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way to write strings to file?

Tags:

python

file-io

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, ?

like image 941
alvas Avatar asked Jan 01 '14 12:01

alvas


1 Answers

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.

like image 108
volcano Avatar answered Nov 10 '22 01:11

volcano