Python - print to a file

Introduction

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

Demo

x = 'test' 
y = 99 #  w  w  w  .  j a v a  2 s.  co  m
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