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

5
  • 4
    I think the first one. Explicit is better than implicit. Commented Jan 1, 2014 at 12:14
  • Agreed. The second is primarily to make C developers feel at home. Commented Jan 1, 2014 at 12:20
  • 2
    In python3, the second will be print('foo bar', file=fout), but the first one keeps the same. Commented Jan 1, 2014 at 12:20
  • You should take a look here for a proper explanation btw Commented Jan 1, 2014 at 12:24
  • These do different things. Even if you stick a comma on the end of the print statement, the soft-space feature will ruin your day. Commented Jan 1, 2014 at 12:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Python 3 changed print to a function, so the syntax is different: print("some string", file=fout)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.