简体   繁体   中英

What is the pythonic way to write strings to file?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM