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).
printdoes thingsfile.writedoesn’t, allowing you to skip string formatting for some basic things.It inserts spaces between arguments and appends the line terminator.
It calls the
__str__or__repr__special methods of an object to convert it to a string.You would have to manually do these things if you used
file.writeinstead ofprint.