Im trying to print output to another file

Viewed 23

This is my code:

data = [['a', 'b', 'c'],['1', '2', '3']]
col_width = max(len(word) for row in data for word in row) + 2
for row in data: 
 print("".join(word.ljust(col_width) for word in row))

this is what I tried:

import sys
data = [['a', 'b', 'c'],['1', '2', '3']]
col_width = max(len(word) for row in data for word in row) + 2
for row in data: 
 print("".join(word.ljust(col_width) for word in row))
original_stdout = sys.stdout
with open('filename.txt', 'w') as f:
    sys.stdout = f
    print("".join(word.ljust(col_width) for word in row))
    sys.stdout = original_stdout  

this is the output I want in the file:

a b c 

1 2 3

this is the output I get when I run my code:

1  2  3 
0 Answers
Related