Python - Automatic stream redirection

Introduction

These redirected forms of print are handy if you need to print to both files and the standard output stream.

Demo

log =  open('log.txt', 'a')             # 3.X 
x = 1# from w w w.  jav a 2  s.  c o m
y='a'
z= [1,2,3]


print(x, y, z, file=log)                # Print to a file-like object 
print(x, y, z)                          # Print to original stdout 

#log =  open('log.txt', 'a')             # 2.X 
log = open('log.txt', 'w') 
print(1, 2, 3, file=log)            # For 2.X: print >> log, 1, 2, 3 
print(4, 5, 6, file=log) 
log.close() 
print(7, 8, 9)                      # For 2.X: print 7, 8, 9

Result

Related Topic