Python 2 or Python 3 API reference:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.
Since file object normally contains write()
method, all you need to do is to pass a file object into its argument.
with open('file.txt', 'w') as f:
print('hello world', file=f)
with open('file.txt', 'a') as f:
print('hello world', file=f)