f.write vs print >> f

Question:

There are at least two ways to write to a file in python:

f = open(file, 'w')
f.write(string)

or

f = open(file, 'w')
print >> f, string     # in python 2
print(string, file=f)  # in python 3

Is there a difference between the two? Or is any one more Pythonic? I’m trying to write a bunch of HTML to file so I need a bunch of write/print statements through my file(but I don’t need a templating engine).

Asked By: oxuser

||

Answers:

The documentation on print might help explain this: print statement (Python 2.7 documentation).

print, by default, prints to standard output, which in fact is a “file-like” object (sys.stdout). The standard output itself has a write() method. Using print >> f seems to be an unnecessary abstraction.

Also, it seems too verbose to me. f.write() is fine.

Answered By: voithos

print does things file.write doesn’t, allowing you to skip string formatting for some basic things.

It inserts spaces between arguments and appends the line terminator.

print "a", "b" # prints something like "a bn"

It calls the __str__ or __repr__ special methods of an object to convert it to a string.

print 1 # prints something like "1n"

You would have to manually do these things if you used file.write instead of print.

Answered By: agf

As a bottonline: do use file.write when writing to files.

The “>>” idiom for printing was borrowed from C++ in Python’s early days, and is rather unpythonic – so much that it no longer exists in Python 3.x – where one can use the print, now a function instead of a statement, to write to a file – but with no special syntax for that.

As @agf points in his answer, using “print” to write to a file does more things than simply calling write – it automatically calls str(obj) to get a string representation of the object, whereas .write require that a (byte) string be passed as parameter – in Python world “explicit is better than implicit”, so one more motive for one to go with file.write instead.

Answered By: jsbueno

This is the preferred way, using context handlers:

with open(file, 'w') as f:
  f.write(string)

On python 2 I prefer file.write because the >> syntax is deprecated. For python 3 you might prefer to use the print function instead, which you should note does some extra things (for example automatically convert numbers to strings for you, etc).

Answered By: wim

I disagree somewhat with several of the opinions expressed here, that print >> f is redundant and should be avoided in favour of f.write.

print and file.write are quite different operations. file.write just directly writes a string to a file. print is more like “render values to stdout as text”. Naturally, the result of rendering a string as text is just the string, so print >> f, my_string and f.write(my_string) are nearly interchangeable (except for the addition of a newline). But your choice between file.write and print should normally be based on what you’re doing; are you writing a string to a file, or are you rendering values to a file?

Sure, print is not strictly necessary, in that you can implement it with file.write. But then file.write is not strictly necessary, because you can implement it with the operations in os for dealing with file descriptors. Really they’re operations on different levels, and you should use whichever is more most appropriate for your use (normally the level other nearby code is working on, or the highest level that doesn’t get in your way).

I do feel that the print >> f syntax is fairly horrible, and is a really good example of why print should have been a function all along. This is much improved in Python 3. But even if you’re writing Python 2 code that you’re planning to port to Python 3, it is much easier to convert print >> f, thing1, thing2, thing3, ... to print(thing1, thing2, thing3, file=f) than it is to convert the circumlocution where you roll your own code to do the equivalent of print‘s rendering and then call f.write(text). I’m pretty sure the semi-automatic converter from Python 2 to Python 3 will even do the conversion for you, which it couldn’t possibly do if you avoid the print >> f form.

Bottom line: use print to render values to stdout (or to a file). Use f.write to write text to a file.

Answered By: Ben

Agree with @agf

I preferred print(..., file=f) because of its flexibility.

with open('test.txt', 'w') as f:
    print('str', file=f)
    print(1, 20, file=f)

It is also easy to convert existing print command.

write accepts only string.

Answered By: wannik

You should not do either of those things. The most Pythonic thing to do is use the Python 3 print function (as opposed to the Python 2 print statement):

f = open(file, 'w')
print(string, file=f)

Of course the ideal way to do this is to just use Python 3. But if you’re stuck using Python 2 you can turn it on using a future statement at the top of the file:

from __future__ import print_function

Note that this changes print in other ways, most obviously in that you need to add brackets around its arguments. But the changes are all improvments, which is the whole reason for the change in Python 3. While you’re at it, consider using all the future statements to get as many backported improvements from Python 3 as possible.

Answered By: Jim Oldfield
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.