oxuser oxuser - 3 months ago 35
Python Question

f.write vs print >> f

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


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).

agf agf
Answer

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 b\n"

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

print 1 # prints something like "1\n"

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

Comments