Python - print to a file

Introduction

You can redirect the printed text to an open output file:

Demo

x = 'test' 
y = 99 #  ww  w  . j a v a 2 s.  c om
z = ['eggs'] 

print(x, y, z, sep='...', file=open('data.txt', 'w'))      # Print to a file 
print(x, y, z)                                             # Back to stdout 
print(open('data.txt').read())                             # Display file text

Result

Related Topic