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